本文介绍了优先级:逻辑或三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下事项:

(编辑:我已稍微修改了该功能以删除三元运算符的使用或大括号)

Consider the following:
( I've amended the function slightly to remove the use or braces with the ternary operator)

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







我知道这可以通过使用大括号轻松修复:


I'm aware that this is easily fixed by using braces:

function range(start,end,step){
  var start = start || 1,
      end = end || 100,
      step = step || ((start < end) ? 1:-1);
  console.log(step);
}







我知道逻辑OR在二进制
逻辑条件运算符中具有最低优先级,但认为 具有更高的
优先级
比条件三元运算符?

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?

我误读了?


推荐答案

是的, || 运算符的优先级高于条件?:运营商。这意味着它首先被执行。从您链接的页面:

Yes, the || operator has higher precedence than the conditional ?: operator. This means that it is executed first. From the page you link:

让我们来看看这里的所有操作:

Let's have a look at all the operations here:

step = step || (start < end) ? 1:-1;

优先级最高的运营商是()分组操作。这里导致 false

The operator with the highest precedence is the () grouping operation. Here it results in false:

step = step || false ? 1 : -1;

下一个最高优先级是逻辑OR运算符。 步骤是真实的,因此导致步骤

The next highest precedence is the logical OR operator. step is truthy, so it results in step.

step = step ? 1 : -1;

现在我们进行三元运算,这是唯一剩下的运作。同样,步骤是真实的,所以第一个选项被执行。

Now we do the ternary operation, which is the only one left. Again, step is truthy, so the first of the options is executed.

step = 1;

这篇关于优先级:逻辑或三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:50