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

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

问题描述

版主注意:请抵制编辑代码或删除此通知的冲动.空白模式可能是问题的一部分,因此不应不必要地篡改.如果您属于空白无关紧要"的阵营,您应该可以接受代码原样.

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.

(a== 1 && a ==2 && a==3) 是否有可能在 JavaScript 中计算为 true?

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.

推荐答案

如果你利用了 == 是如何工作的,您可以简单地创建一个带有自定义 toString(或 valueOf) 函数,每次使用时都会更改返回的内容,以满足所有三个条件.

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!');
}

之所以有效,是因为使用了松散相等运算符.使用松散相等时,如果一个操作数的类型与另一个不同,引擎将尝试将一个转换为另一个.在左边的对象和右边的数字的情况下,它会尝试通过首先调用 valueOf 来尝试将对象转换为数字(如果它是可调用的),如果失败,它将调用 <代码>toString.我在这种情况下使用 toString 只是因为它是我想到的,valueOf 会更有意义.如果我改为从 toString 返回一个字符串,引擎就会尝试将该字符串转换为一个数字,从而得到相同的最终结果,尽管路径稍长.

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 &amp;&amp; a ==2 &amp;&amp; a==3) 可以评估为真吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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