我附上了一个带有两个 if 条件的例子。第一个 if 条件按预期工作。第二个 if 条件返回 11,但为什么呢?我知道第二个 if 条件是错误的,但我想了解为什么 Javascript 在这种情况下返回 11。
function exception(number) {
// if(number === 10 || number === 11) { // Working as expected
if(number === 10 || 11) { // Why 11?
console.log(number);
}
}
function loop(f) {
for (i = 0; i <= 100; i++) {
f(i);
}
}
loop(exception);
最佳答案
来自 this question .
(expr1 || expr2)
"Returns expr1 if it can be converted to true; otherwise, returns expr2."
因此,当 expr1
是(或计算为)这些 0,"",false,null,undefined,NaN
之一时,则 expr2
返回,否则返回 expr1
关于javascript - 逻辑运算符 ||返回数字而不是 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34706372/