JavaScript运算符优先级、赋值和递增?

huangapple go评论63阅读模式
英文:

JavaScript Operator Precedence, Assignment, and Increment?

问题

在JavaScript(JS)中,++的优先级高于+==。在尝试更好地理解JS中操作符执行顺序的过程中,我希望看到为什么以下代码片段会导致打印出30

let i = 1
let j = (i+=2) * (i+=3 + ++i);
console.log(j); //prints 30

从表面上看,似乎是i+=2首先执行,导致3 * (i+=3 + ++i),然后3作为i的起始值同时用于i+=3++i(导致3 * (6 + 4))。但我在想,如果是这样的话,为什么要执行++ii+=3的副作用以将其分配给i在另一个执行之前发生呢?

英文:

In JavaScript (JS), ++ has higher precedence than += or =. In trying to better understand operator execution order in JS, I'm hoping to see why the following code snippet results in 30 being printed?

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let i = 1
let j = (i+=2) * (i+=3 + ++i);
console.log(j); //prints 30

<!-- end snippet -->

Naively, it seems like the i+=2 is executing first, resulting in 3 * (i+=3 + ++i), and then 3 is being used as the starting value for i for both the i+=3 and ++i (resulting in 3 * (6 + 4)). But I'm wondering, if that is the case, why either the ++i or i+=3 is not having its side effect in assigning to i occur before the other executes?

答案1

得分: 2

评论讨论摘要:

简化示例:

let i = 1
let j = i += 3 + ++i;
console.log(j); // 输出 6

i += 3 + ++i 等同于 i += (3 + ++i) 而不是 (i += 3) + (++i)

ECMAScript 规范 中,我们可以看到左侧表达式先进行评估

  1. 让 lref 为 LeftHandSideExpression 的评估结果。

然后在步骤 7 中进行右侧计算

  1. 让 r 为 ApplyStringOrNumericBinaryOperator(lval, opText, rval) 的结果。

因此,i += (3 + ++i) 实际上是:

let lhs = i // 1
let rhs = 3 + ++i // 3 + 2
i = lhs + rhs // 6

或者在问题中的示例中:

let lhs = i // 3
let rhs = 3 + ++i // 3 + 4
i = lhs + rhs // 10
英文:

Summary of the discussion in comments:

Simplified example:
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let i = 1
let j = i += 3 + ++i;
console.log(j); //prints 6

<!-- end snippet -->

i += 3 + ++i is the same as i += (3 + ++i) and not (i += 3) + (++i)

In the ECMAScript specification we can read that left-hand side expression is evaluated first

> 1. Let lref be ? Evaluation of LeftHandSideExpression.

Then after right-hand side calculations in step 7

> 7. Let r be ? ApplyStringOrNumericBinaryOperator(lval, opText, rval).

So i += (3 + ++i) is really:

let lhs = i // 1
let rhs = 3 + ++i // 3 + 2
i = lhs + rhs // 6

or in thee example from the question:

let lhs = i // 3
let rhs = 3 + ++i // 3 + 4
i = lhs + rhs // 10

huangapple
  • 本文由 发表于 2023年6月22日 03:37:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定