gpt4 book ai didi

javascript - Javascript 中的预增量

转载 作者:可可西里 更新时间:2023-11-01 02:24:55 24 4
gpt4 key购买 nike

我刚刚在 Javascript 中遇到了一个关于预增量的“特性”。在我使用过的所有其他语言中,它就像我想象的那样。例如。在 C++ 中:

#include <iostream>

int main()
{
int i = 0;

i += ++i;

std::cout << i << std::endl; // Outputs 2.
}

因此,++i 不会复制变量,因此输出为 2。

在 PHP 中相同:

<?php

$i = 0;

$i += ++$i;

echo $i; // Outputs 2.

但是,在 Javascript 中:

var i = 0;

i += ++i;

console.log(i); // Outputs 1.

所以它看起来像在 Javascript 中,它复制 i 并且不引用该变量。这是故意的吗?如果是,为什么?

最佳答案

来自 EcmaScript 标准:

11.4.4 Prefix Increment Operator

The production UnaryExpression : ++ UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.
  2. Throw a SyntaxError exception if the following conditions are all true: �
    • Type(expr) is Reference is true
    • IsStrictReference(expr) is true
    • Type(GetBase(expr)) is Environment Record
    • GetReferencedName(expr) is either "eval" or "arguments"
  3. Let oldValue be ToNumber(GetValue(expr)).
  4. Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 11.6.3).
  5. Call PutValue(expr, newValue).
  6. Return newValue.

11.13.2 Compound Assignment ( op= )

The production AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression, where AssignmentOperator is @= and @ represents one of the operators indicated above, is evaluated as follows:

  1. Let lref be the result of evaluating LeftHandSideExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating AssignmentExpression.
  4. Let rval be GetValue(rref).
  5. Let r be the result of applying operator @ to lval and rval.
  6. Throw a SyntaxError exception if the following conditions are all true:
    • Type(lref) is Reference is true
    • IsStrictReference(lref) is true
    • Type(GetBase(lref)) is Environment Record
    • GetReferencedName(lref) is either "eval" or "arguments"
  7. Call PutValue(lref, r)

因此,var i = 0; i +=++i 是:

i = 0;
lvalue = value(i), which is 0;
rvalue = value(++i), which is: increment i, then value of i (1);
thus, rvalue = 1;
i = lvalue (0) + rvalue (1), which is 1.

完全符合规范。

但是,在 C++ 中,这被明确定义为未定义的行为,因此在不同的编译器上,您也可能得到 1。或 99。或者它可能会使您的计算机着火。所有这些都是符合标准的编译器。因此,大多数人会建议您在一条语句中只使用一次前/后递增变量。

关于javascript - Javascript 中的预增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23930661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com