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?
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
)函数创建一个对象,该对象每次使用时都会改变其返回的内容,以满足所有三个条件。
const a = {
i: 1,
toString: function () {
return a.i++;
}
}
if(a == 1 && a == 2 && a == 3) {
console.log('Hello World!');
}
我无法抗拒 - 其他答案无疑是真实的,但你真的不能走过以下代码:
var aᅠ = 1;
var a = 2;
var ᅠa = 3;
if(aᅠ==1 && a== 2 &&ᅠa==3) {
console.log("Why hello there!")
}
有可能的!
var i = 0;
with({
get a() {
return ++i;
}
}) {
if (a == 1 && a == 2 && a == 3)
console.log("wohoo");
}
链接地址: http://www.djcxy.com/p/8440.html
上一篇: 如何在HTML页面上显示原始JSON数据