var a = "ab";
var b = "ab";
a+=1; // "ab1"
b++; // "NaN"
(Tested on chrome's V8)
Can someone explain why the results are different based on the internal atomic actions of the ++
arithmetic operator and the +开发者_运维知识库=
assignment operator with argument 1
++
converts to number, and then increments, +=
with a String concatenates.
From the spec:
11.3.1 Postfix Increment Operator
...
3. LetoldValue
beToNumber(GetValue(lhs))
.
4. LetnewValue
be the result of adding the value 1 tooldValue
, using the same rules as for the+
operator (see 11.6.3).
For the a+=1
case, if you add a number to a string or the other way around the number gets converted to a string:
11.6.1 The Addition operator ( + )
...
7. IfType(lprim)
is String orType(rprim)
is String, then
a. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).
++
tries to increment a Number (if it's not a number, this will fail - resulting inNaN
)+=
is concatenation, in this case the JavaScript engine figures out that one side is a string, so they're both concatenated as strings.
They're different because they're different operations, ++
is specifically an arithmetic operator, where as +=
is a more general assignment operator that behaves differently based on the data type - specifically, string has its own implementation.
That's because the + operator in javascript is both the mathematical + and the string concatenation operator, while the ++ is always a mathematical operator.
So, when you have:
string = string + number;
the number is converted to string and concatenated to the first string.
When you have
string++
you will convert the string to a number, getting NaN, and then add one to that - getting still, NaN.
精彩评论