考虑以下:
(编辑:我稍微修改了函数以删除使用三元运算符的使用或大括号)
function someFunction(start,end,step){
var start = start || 1,
end = end || 100,
boolEndBigger = (start < end); // define Boolean here
step = step || boolEndBigger ? 1:-1;
console.log(step);
}
someFunction()
// step isn't defined so expect (1<10) ? 1:-1 to evaluate to 1
someFunction(1,10)
// again step isn't defined so expect to log 1 as before
The problem:
someFunction(1,10,2) //step IS defined, shortcut logical OR || should kick in, //step should return 2 BUT it returns 1
我知道这很容易通过使用大括号来解决:
function range(start,end,step){
var start = start || 1,
end = end || 100,
step = step || ((start < end) ? 1:-1);
console.log(step);
}
The question: Why doesn't the
||
operator get short-cut in this case?I'm aware that the Logical OR has the lowest precedence among binary logical conditional operators but thought that it has higher precedence than the conditional Ternary operator?
Am I misreading the MDN docs for Operator precedence?
最佳答案
是的,||
运算符的优先级高于条件 ?:
运算符(operator)。这意味着它首先被执行。从您的页面 link :
Operator precedence determines the order in which operators are evaluated. Operators with higher precedence are evaluated first.
让我们看看这里的所有操作:
step = step || (start < end) ? 1:-1;
具有最高优先级的运算符是 ()
分组操作。这里结果为 false
:step = step || false ? 1 : -1;
下一个最高优先级是逻辑 OR 运算符。 step
是真实的,所以结果是 step
.step = step ? 1 : -1;
现在我们进行三元运算,这是唯一剩下的一个。再次,step
是真实的,所以第一个选项被执行。step = 1;
关于javascript - 优先级 : Logical or vs. 三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42026158/