JavaScript ++ 运算符无法正常工作

JavaScript ++ operator not working correctly

为什么当我 运行 下面的 JavaScript 代码时,它会提示 10?我希望它会提醒 11。我在多个浏览器中尝试过。

var t=5;
t+=t++;
alert(t);

这是因为您使用了 t++ 而不是 ++t 第一个先评估数字然后递增,而第二个则相反。

t = 5; t += ++t // => 11

您似乎假设给定 left += rightright 首先被计算 ,然后添加到 left。然而,事实并非如此。

来自spec

12.14.4 Runtime Semantics: Evaluation

AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression

  1. Let lref be the result of evaluating LeftHandSideExpression.
  2. Let lval be GetValue(lref).
  3. ...

如你所见,左边先于右边求值,即 t 先于 t++ 求值,此时 t 仍然是 5.

假设t = 5

,让我们重写几次以展开每一步
t += t++;
// same as
t = t + t++;
// same as
t = 5 + t++;
// same as
t = 5 + (t = t + 1, 5); // the second 5 here is the old `t` value
// same as
t = 5 + 5; // the `t = t + 1` becomes obsoleted by the other `t =`
// same as
t = 10;

那么我们学到了什么?手写,

t = t + t + 1;
// or
t = 2 * t + 1;
// or if you really like +=
t += t + 1;

如果您想知道为什么 t++(t = t + 1, 5) 相同,那是因为 foo++ 的定义方式,它表示

  1. 记住foo的值,我们称它为old_foo
  2. foo 增加 1
  3. Return old_foo

如果我们把它写成一个函数,伪代码

function (foo) { // passing foo by reference
    var old_foo = foo;
    foo = foo + 1; // imaging this is a reference set
    return old_foo;
}

或者,使用 comma operator

foo = foo + 1, old_foo;
// i.e. if `foo` was `5`
foo = foo + 1, 5;