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 exampleObject
typeNumber
when compared type,Object
type will be converted toNumber
type.Object
converted toNumber
, it will try to callObject.valueOf()
andObject.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 calltoString()
will implicitly call theArray.join()
method and the usage of theshift
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 theshift()
method will do nothing and return the value ofundefined
Please note that this method does not create a new array, but directly modifies the original array. So we can see thata == 1
is called whentoString()
,toString()
called forjoin()
,join()
is equal toshift
, then it is converted toNumber
type.
var a = [1, 2, 3];
a.join = a.shift;
console.log(a == 1 && a == 2 && a == 3); // true
defineProperty
Use adefineProperty
, let the return value ofa
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]
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。