请考虑以下内容:
(编辑:我稍微修改了函数,以消除三目运算符中使用括号的情况)
问题: 为什么在这种情况下“||”运算符不会被快捷方式替代? 我知道逻辑或(Logical OR)是二元逻辑条件运算符中优先级最低的,但我认为它比条件三元运算符具有更高的优先级? 我是否误读了MDN运算符优先级文档?
(编辑:我稍微修改了函数,以消除三目运算符中使用括号的情况)
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);
}
问题: 为什么在这种情况下“||”运算符不会被快捷方式替代? 我知道逻辑或(Logical OR)是二元逻辑条件运算符中优先级最低的,但我认为它比条件三元运算符具有更高的优先级? 我是否误读了MDN运算符优先级文档?
(step || (start < end)) ? 1 : -1
进行评估。 - Niet the Dark Absol