Javascript ++ vs +=1

前端 未结 3 1121
轻奢々
轻奢々 2020-12-10 05:22
var a = \"ab\";
var b = \"ab\";
a+=1; // \"ab1\"
b++; // \"NaN\"

(Tested on chrome\'s V8)

Can someone explain why the results are different

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-10 05:53

    ++ converts to number, and then increments, += with a String concatenates.

    From the spec:

    11.3.1 Postfix Increment Operator

      ...
      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).

    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. If Type(lprim) is String or Type(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).

提交回复
热议问题