JavaScript基础(JavaScript Basic)
First for ++
关于运算符++
的规范,思考问题
1 | let num = 0; |
1 | let num = "5"; |
相关文档
13.4.2.1 Runtime Semantics: Evaluation
UpdateExpression : LeftHandSideExpression ++
- Let lhs be ? Evaluation of LeftHandSideExpression.
- Let oldValue be ? ToNumeric(? GetValue(lhs)).
- If oldValue is a Number, then
a. Let newValue be Number::add(oldValue, 1𝔽). - Else,
a. Assert: oldValue is a BigInt.
b. Let newValue be BigInt::add(oldValue, 1ℤ). - Perform ? PutValue(lhs, newValue).
- Return oldValue.
13.4.4.1 Runtime Semantics: Evaluation
UpdateExpression : ++ UnaryExpression
- Let expr be ? Evaluation of UnaryExpression.
- Let oldValue be ? ToNumeric(? GetValue(expr)).
- If oldValue is a Number, then
a. Let newValue be Number::add(oldValue, 1𝔽). - Else,
a. Assert: oldValue is a BigInt.
b. Let newValue be BigInt::add(oldValue, 1ℤ). - Perform ? PutValue(expr, newValue).
- 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:
- Let primValue be ? ToPrimitive(value, number).
- If primValue is a BigInt, return primValue.
- Return ? ToNumber(primValue).
以上摘自官方文档,其中,下标𝔽指的是Numbers,下标ℤ指的是BigInts,通过官方文档,表明了无论++ num
还是num ++
都会进行数字转换再进行相加,而不是单纯的num = num + 1
,再一次验证结果如下:
1 | let num = "e"; |
另外,从之中可以看出,++n
是返回新的结果值,n++
返回的是旧的结果值
而num = num + 1
只进行了加法运算