6
头图

Hello, everyone. I am Lin Sanxin. Another week has passed. Hey, I'm annoyed when I think about it when I get older. Suddenly someone asked me today:

(a == 1 && a == 2 && a == 3) is it possible to be true

I just wanted to kick it over, aren't you kidding me? When my foot was a centimeter away from his face, I suddenly found out, eh! It seems a bit interesting

Object type conversion

When two types are different when == comparison is performed, one type is converted to another type, and then the comparison is performed. For example Object type Number when compared type, Object type will be converted to Number type. Object converted to Number , it will try to call Object.valueOf() and Object.toString() to obtain the corresponding number basic types.
var a = {
    i: 1,
    toString: function () {
        return a.i++;
    }
}
console.log(a == 1 && a == 2 && a == 3) // true

Array type conversion

As with the above type conversion, the array call toString() will implicitly call the Array.join() method and the usage of the shift shift() method is used to delete the first element of the array and return the value of the first element. If the array is empty, then the shift() method will do nothing and return the value of undefined Please note that this method does not create a new array, but directly modifies the original array. So we can see that a == 1 is called when toString() , toString() called for join() , join() is equal to shift , then it is converted to Number type.
var a = [1, 2, 3];
a.join = a.shift;
console.log(a == 1 && a == 2 && a == 3); // true

defineProperty

Use a defineProperty , let the return value of a
var val = 0;
Object.defineProperty(window, 'a', { // 这里要window,这样的话下面才能直接使用a变量去 ==
    get: function () {
        return ++val;
    }
});
console.log(a == 1 && a == 2 && a == 3) // true
Did you lose school?

Concluding remarks

I am Lin Sanxin, an enthusiastic front-end rookie programmer. If you are motivated, like the front-end, and want to learn the front-end, then we can make friends, fish together haha, fish school, add me, please note [think]

image.png


Sunshine_Lin
2.1k 声望7.1k 粉丝