javascript - 优先级 : Logical or vs. 三元运算符

标签 javascript ternary-operator operator-precedence logical-or

考虑以下:
(编辑:我稍微修改了函数以删除使用三元运算符的使用或大括号)

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/

相关文章:

ruby - 为什么 "true or true and false"看起来同时为真和假?

javascript - 将多条 JSON 记录读取到数组中

c# - 三元(条件)运算符与返回 Action 的 if 语句之间的区别

javascript 三元运算符与 if/else 相反

f# - 是否可以在 F# 中使用正常顺序评估

c - 是 'if'条件下被忽略的运算符的优先级

javascript - 移动网页的 Twitter 身份验证?

javascript - 未捕获的类型错误 : Cannot read property 'submit' of null for stripe payment

javascript - 告诉 css 动画结束的 js 警报

ios - 如何进一步缩短三元运算符