(A == 1 && a == 2 && a == 3) there is likely to be true right?

 (A == 1 && a == 2 && a == 3) there is likely to be true right?

When a == 1 && a == 2 && a == 3 is true?

Solution one: Object type conversion

var a = {
    i:1,
    toString:function(){ return a.i++; } }

When two types == comparison is not performed at the same time, it will be converted to a type of another type, and then compared.

For example, when compared with the type Object type Number, Object types will be converted to Number type.

When the object is converted to Number, it will try to call Object.valueOf () and Object.toString () to get the basic numbers corresponding to the type.

Solution two: array type conversion

var a = [1,2,3];
a.join = a.shift; console.log(a == 1 && a == 2 && a == 3);

This type of conversion as above, an array of calling toString () implicitly calls Array.join () method

Use of the method of the array shift: shift () method is used to remove the first element of the array from which, and returns the value of the first element. If the array is empty, then the shift () method will do nothing, returning undefined value. Note that this method does not create a new array, but directly modify the original arrayObject.

So we can see that  a==1would be called when toString (), toString () calls the join (), join () is equal to shift, then converted to Number of type 1.

Solution three: the definition of get a

var val = 0;
Object.defineProperty(window, 'a', { get: function() { return ++val; } }); console.log(a == 1 && a == 2 && a == 3);

Use a get, so that three different values ​​of a return value.

Guess you like

Origin www.cnblogs.com/login123/p/12155616.html