英文:
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)
)。但我在想,如果是这样的话,为什么要执行++i
或i+=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 规范 中,我们可以看到左侧表达式先进行评估
- 让 lref 为 LeftHandSideExpression 的评估结果。
然后在步骤 7
中进行右侧计算
- 让 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论