Why doesn't the shorthand arithmetic operator ++ after the variable name return 2 in the following statement?

前端 未结 3 1135
-上瘾入骨i
-上瘾入骨i 2020-11-27 22:10

I have a very simple arithmetic operator but am at my wits end why it doesn\'t return 2. The code below returns 1. I thought that x++ equates to x = x + 1;

C

3条回答
  •  生来不讨喜
    2020-11-27 22:38

    If you take a look at the javascript specification pages 70 and 71 you can see how it should be implemented:

    Prefix:

    1. Let expr be the result of evaluating UnaryExpression.
    2. Throw a SyntaxError exception if the following conditions are all true:72 © Ecma International 2011
      • 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.

    Or more simply:

    1. Increment value
    2. Return value

    Postfix:

    1. Let lhs be the result of evaluating LeftHandSideExpression.
    2. Throw a SyntaxError exception if the following conditions are all true:
      • Type(lhs) is Reference is true
      • IsStrictReference(lhs) is true
      • Type(GetBase(lhs)) is Environment Record
      • GetReferencedName(lhs) is either "eval" or "arguments"
    3. Let oldValue be ToNumber(GetValue(lhs)).
    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(lhs, newValue).
    6. Return oldValue.

    Or more simply:

    1. Assign value to temp
    2. Increment value
    3. Return temp

提交回复
热议问题