If you take advantage of how ==
works , you could simply create an object with a custom toString
(or valueOf
) function that changes what it returns each time it is used such that it satisfies all three conditions.
(如果您利用==
如何工作 ,您可以简单地创建一个具有自定义toString
(或valueOf
)函数的对象,该函数会在每次使用时更改它返回的内容,以使其满足所有三个条件。)
const a = { i: 1, toString: function () { return a.i++; } } if(a == 1 && a == 2 && a == 3) { console.log('Hello World!'); }
The reason this works is due to the use of the loose equality operator.
(这种方法的原因是由于使用了松散的等式运算符。)
When using loose equality, if one of the operands is of a different type than the other, the engine will attempt to convert one to the other.(当使用松散相等时,如果其中一个操作数与另一个操作数的类型不同,则引擎将尝试将一个操作数转换为另一个操作数。)
In the case of an object on the left and a number on the right, it will attempt to convert the object to a number by first calling valueOf
if it is callable, and failing that, it will call toString
.(如果左边的对象和右边的数字,它将尝试通过首先调用valueOf
将对象转换为数字(如果它是可调用的),如果失败,它将调用toString
。)
I used toString
in this case simply because it's what came to mind, valueOf
would make more sense.(我在这种情况下习惯使用toString
只是因为它是我想到的, valueOf
会更有意义。)
If I instead returned a string from toString
, the engine would have then attempted to convert the string to a number giving us the same end result, though with a slightly longer path.(如果我从toString
返回一个字符串,那么引擎会尝试将字符串转换为给出相同最终结果的数字,但路径稍长。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…