即使 if 语句为 false,下面的 else 语句也不会执行。我想我犯了一些非常基本的错误,但不知道是什么。
var a = ["king","queen","100"];
for (var i=0; i<a.length; i++) {
if (a[i] === "king" || "queen"){
console.log("monarch");
}
else {
console.log("The number is: "+ parseInt(a[i]));
}
}
// This prints out "monarch" 3 times
最佳答案
应该是:
var a = ["king","queen","100"];
for (var i=0; i<a.length; i++) {
if (a[i] === "king" || a[i] === "queen"){
console.log("monarch");
}
else {
console.log("The number is: "+ parseInt(a[i]));
}
}
您以我们口语的方式编写 bool 表达式,“A 是 1 或 2”。这不是 OR
的解释方式。
OR
的左侧为 true
:a[i] === "king"
为 true
;或者OR
的右侧是true
:“queen”
。它自行计算字符串,并且字符串 "queen"
不是 null
,因此它的计算结果为 true
。
关于javascript - 奇怪的 if-else 行为 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40574780/