How to set (a == 1 && a == 2 && a == 3) to true (a == 1 && a == 2 && a == 3)

Idea 1: Implicit conversion

The first thing that comes to mind is the implicit conversion that occurs when == is used to solve this problem. When a complex type is implicitly converted to number, valueOf() is first used to get the original value, and if the original value is not number, toString() is used to convert it to a string. There are two solutions: The valueOf and toString

valueOf

const a = {
	n : 1,
    valueOf:() => {
    	return a.n++
    }
}
console.log(a == 1 &&  a == 2 && a == 3); //true
Copy the code

toString

Const a = [1, 2, 3]; a.toString = a.shift; console.log(a == 1 && a == 2 && a == 3); //trueCopy the code

Symbol. ToPrimitive

The Symbol. ToPrimitive function is triggered when the object is converted to its original value, and a can be modified

let n = 1; const a = { [Symbol.toPrimitive](hint) { return n++; }}; console.log(a == 1 && a == 2 && a == 3); //trueCopy the code

Object. DefinedProperty

DefinedProperty (a === 1 && A ===2 && a === 3) is also true

let n = 1;
Object.definedProperty(window, 'a',{
	get: function(){
    	return n++;
    }
})
console.log(a == 1 && a ==2 && a == 3);
Copy the code

There are several ways to make (a == 1&&a == 2&&a == 3) true, and there are a few problems with summarizing these methods

1, Proxy

Object.definedproperty is used as a Proxy, but in practice, the Proxy needs an instance to hijack the property of window, which cannot be set to Window. A ==2 && proxy. A == 3

2, using Symbol. ToPrimitive found this problem

ToPrimitive is a built-in Symbol value, which exists as the function value attribute of the object. There is no n in the execution context of the Symbol. Therefore, it is necessary to put n outside the Symbol.