Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

javascript - 可以(a == 1 && a == 2 && a == 3)评估为真吗?(Can (a== 1 && a ==2 && a==3) ever evaluate to true?)

Moderator note: Please resist the urge to edit the code or remove this notice.

(主持人注意:请拒绝编辑代码或删除此通知的冲动。)

The pattern of whitespace may be part of the question and therefore should not be tampered with unnecessarily.

(空白模式可能是问题的一部分,因此不应该被不必要地篡改。)

If you are in the "whitespace is insignificant" camp, you should be able to accept the code as is.

(如果你在“空白是微不足道的”阵营,你应该能够接受原样。)

Is it ever possible that (a== 1 && a ==2 && a==3) could evaluate to true in JavaScript?

(是否有可能(a== 1 && a ==2 && a==3)可以在JavaScript中评估为true ?)

This is an interview question asked by a major tech company.

(这是一家大型科技公司提出的面试问题。)

It happened two weeks back, but I'm still trying to find the answer.

(它发生在两周前,但我仍在努力寻找答案。)

I know we never write such code in our day-to-day job, but I'm curious.

(我知道我们从来没有在日常工作中写过这样的代码,但我很好奇。)

  ask by Dimpu Aravind Buddha translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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返回一个字符串,那么引擎会尝试将字符串转换为给出相同最终结果的数字,但路径稍长。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...