优先级:逻辑或与三元运算符

Precedence: Logical or vs. 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

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?

是的,|| 运算符的优先级高于条件运算符 ?:。这意味着它首先被执行。从您的页面 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 是松散类型的,这意味着只要运算符或语句需要特定的数据类型,JavaScript 就会自动将数据转换为该类型。

让我们看看它如何转换为其他类型的一些场景

示例 1.

if() 语句需要一个布尔值, 因此,您在括号中定义的任何内容都将转换为布尔值。

JavaScript 值通常被称为 "truthy" 或 "falsey",具体取决于此类转换的结果(即真或假)。

记住一个值是否为真,除非已知它是假的。

幸运的是只有六个 falsey -

  1. 假(当然!)
  2. 未定义
  3. 0(数字零)
  4. ""(空字符串)
  5. NaN(不是数字)

示例 2.

var x = 动物园 ||星级 ;

如果 zoo 的计算结果为真,则返回 zoo 的值,否则返回 star 的值

示例 3.

var str = '1' || '2';

'1' 不是假的,因此将返回 '1' 结果:str = '1';

示例 4.

var str = '1' || (true) ? '2' : '3';

首先||(逻辑或)运算符的优先级大于?(有条件的) 运算符

所以首先 ( '1' || (true) ) 将首先被评估

“1”不是假的,因此将返回“1”

中间结果:str = '1' ?' 2' : '3'

“1”不真实,因此将返回“2”

最终结果:str = '2'

示例 5.

var str = '1' || (false) ? '2' : '3';

首先||(逻辑或)运算符的优先级大于?(有条件的) 运算符

所以首先 ( '1' || (false) ) 将首先被评估

“1”不是假的,因此将返回“1”

中间结果:str = '1' ?' 2' : '3'

“1”不真实,因此将返回“2”

最终结果:str = '2'

现在在你的场景中很容易理解:)