Why does JavaScript handle the plus and minus operators between strings and numbers differently?

前端 未结 7 1915
再見小時候
再見小時候 2020-11-22 10:21

I don\'t understand why JavaScript works this way.

console.log(\"1\" + 1);
console.log(\"1\" - 1);

The first line prints 11, and the second

7条回答
  •  借酒劲吻你
    2020-11-22 10:35

    Because the spec explicitly tells to do so. Page 75. Note the difference between 11.6.1 steps 5-8 and 11.6.2 steps 5-7.

    11.6.1 - describes how addition operator works

    1-4. ...

    5. Let lprim be ToPrimitive(lval).

    6. Let rprim be ToPrimitive(rval).

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

    7a. 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 - describes how subtraction operator works

    1-4. ...

    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

    Summary In case of addition if any of the operands when converted to primitive value without any hints suddenly becomes a string the second one is converted to a string too. In case of subtraction both operands are converted to a number.

提交回复
热议问题