Adding and subtracting strings and numbers in Javascript - auto type conversion?

前端 未结 5 1803
抹茶落季
抹茶落季 2020-12-04 01:52

Let\'s look at the following Javascript code.



        
5条回答
  •  失恋的感觉
    2020-12-04 02:21

    The + operator is overloaded. If any operand is a string, string concatenation is performed. If you have two numbers, addition is performed. The - is not overloaded in such a way and all operands are converted to numbers.

    From the specification:

    11.6.1 The Addition operator ( + )

    (...)
    7. If Type(lprim) is String or Type(rprim) is String, then

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

    11.6.2 The Subtraction Operator ( - )

    (...)
    5. Let lnum be ToNumber(lval).
    6. Let rnum be ToNumber(rval).
    7. Return the result of applying the subtraction operation to lnum and rnum.
    (...)

提交回复
热议问题