Can (a== 1 && a ==2 && a==3) ever evaluate to true?
我们可能知道
loose equality operator (==)
将尝试将这两个值转换为公共类型。因此,将调用某些函数。
ToPrimitive(A)
通过调用不同的
A.toString
和
A.valueOf
所以下面的代码将按预期工作。
const a = {
i: 1,
toString: function () {
return a.i++;
}
}
if(a == 1 && a == 2 && a == 3) {
console.log('Never catch!');
}
然而,问题在于
strict equality (===)
. 方法,例如
.valueOf
,
.toString
,或
Symbol.toPrimitive
const a = {
i: 1,
toString: function () {
return a.i++;
}
}
if(a === 1 && a === 2 && a === 3) {
console.log('Never catch!');
}