Article December 12, 2022

JavaScript Basic For ++

Words count 5.4k Reading time 5 mins. Read count 0

JavaScript基础(JavaScript Basic)

First for ++

关于运算符++的规范,思考问题

1
2
3
4
5
6
let num = 0;
num ++;
let secNum = 0;
++ secNum;
//以上两者会输出什么
//答案是num是0,secNum是1
1
2
3
4
5
6
7
let num = "5";
num = num + 1;
let secNum = "5";
secNum ++;
secNum
//以上两者会输出什么
//num的结果是"51",字符串类型,secNum的结果是6,数字类型

相关文档


13.4.2.1 Runtime Semantics: Evaluation
UpdateExpression : LeftHandSideExpression ++

  1. Let lhs be ? Evaluation of LeftHandSideExpression.
  2. Let oldValue be ? ToNumeric(? GetValue(lhs)).
  3. If oldValue is a Number, then
    a. Let newValue be Number::add(oldValue, 1𝔽).
  4. Else,
    a. Assert: oldValue is a BigInt.
    b. Let newValue be BigInt::add(oldValue, 1ℤ).
  5. Perform ? PutValue(lhs, newValue).
  6. Return oldValue.

13.4.4.1 Runtime Semantics: Evaluation
UpdateExpression : ++ UnaryExpression

  1. Let expr be ? Evaluation of UnaryExpression.
  2. Let oldValue be ? ToNumeric(? GetValue(expr)).
  3. If oldValue is a Number, then
    a. Let newValue be Number::add(oldValue, 1𝔽).
  4. Else,
    a. Assert: oldValue is a BigInt.
    b. Let newValue be BigInt::add(oldValue, 1ℤ).
  5. Perform ? PutValue(expr, newValue).
  6. Return newValue.

6.1.6.2 The BigInt Type
The BigInt type represents an integer value. The value may be any size and is not limited to a particular bit-width. Generally, where not otherwise noted, operations are designed to return exact mathematically-based answers. For binary operations, BigInts act as two’s complement binary strings, with negative numbers treated as having bits set infinitely to the left.


7.1.3 ToNumeric ( value )
The abstract operation ToNumeric takes argument value (an ECMAScript language value) and returns either a normal completion containing either a Number or a BigInt, or a throw completion. It returns value converted to a Number or a BigInt. It performs the following steps when called:

  1. Let primValue be ? ToPrimitive(value, number).
  2. If primValue is a BigInt, return primValue.
  3. Return ? ToNumber(primValue).

以上摘自官方文档,其中,下标𝔽指的是Numbers,下标ℤ指的是BigInts,通过官方文档,表明了无论++ num还是num ++都会进行数字转换再进行相加,而不是单纯的num = num + 1,再一次验证结果如下:

1
2
3
4
5
6
7
let num = "e";
num = num + 1;
console.log(num);
let secNum = "e";
secNum++;
console.log(secNum);
//其中的结果是,num为e1,secNum为NaN

另外,从之中可以看出,++n是返回新的结果值,n++返回的是旧的结果值
num = num + 1只进行了加法运算

0%