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

查看:137
本文介绍了可以(a == 1& a = a = 2&& a == 3)评估为真吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


主持人备注:请拒绝编辑代码或删除此通知的冲动。空白模式可能是问题的一部分,因此不应该被不必要地篡改。如果你在空白无关紧要的阵营,你应该能够接受原样。


是否有可能(a == 1&& a == 2&& a == 3)可评估为 true



这是一家大型科技公司提出的面试问题。它发生在两周前,但我仍在努力寻找答案。我知道我们从来没有在日常工作中写过这样的代码,但我很好奇。

解决方案

如果你拿如何 == 有效,您只需使用自定义 toString (或 valueOf )函数创建一个对象它会改变每次使用时返回的内容,使其满足所有三个条件。



  const a = {i:1,toString:function(){return a.i ++;如果(a == 1&& a == 2&& a == 3){console.log('Hello World!');}  






这种方法起作用的原因是由于使用了松散的等式运算符。当使用松散相等时,如果其中一个操作数的类型与另一个不同,则引擎将尝试将一个操作数转换为另一个。如果左边的对象和右边的数字,它将尝试通过首先调用 valueOf 将对象转换为数字,如果它是可调用的,并且失败那,它将调用 toString 。在这种情况下,我使用 toString 只是因为它是我想到的, valueOf 会更有意义。如果我改为从返回字符串,则引擎会尝试将字符串转换为给出相同最终结果的数字,但路径稍长。 / p>

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?

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.

解决方案

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.

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. I used toString in this case simply because it's what came to mind, valueOf would make more sense. 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.

这篇关于可以(a == 1& a = a = 2&& a == 3)评估为真吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆