【发布时间】:2017-06-20 22:30:14
【问题描述】:
请考虑以下几点:
(编辑:我稍微修改了函数以删除使用三元运算符的 use 或大括号)
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);
}
问题: 在这种情况下,为什么
||运算符没有捷径?我知道逻辑或在二进制中的优先级最低 逻辑条件运算符,但认为它 具有更高的 优先级高于条件三元运算符?
【问题讨论】:
-
“更高的优先级”意味着您的代码被评估为
(step || (start < end)) ? 1 : -1 -
“更高优先级”意味着首先评估
||,即首先评估step || (start < end)。 -
@NiettheDarkAbsol:这意味着三元具有更高的优先级,对吧? MDN 文档另有说明...
-
@Xufox:如果是这样,那么第三次调用将返回 2。它不会...
-
@Pineda No...
step || (start < end) ? 1 : -1评估为step ? 1 : -1因为首先评估||而step是真实的。然后,step ? 1 : -1被评估为1,因为step是真实的。
标签: javascript ternary-operator operator-precedence logical-or