考虑以下内容:(
编辑:我稍微修改了函数以删除使用三元运算符的使用或大括号)
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
问题:
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);
}
问题:在这种情况下, 为什么
||
操作员没有捷径?我知道逻辑 OR 在二元逻辑条件运算符中的优先级最低,但认为它的优先级高于条件三元运算符?
我是否误读了MDN 文档中的运算符优先级?