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

前端 未结 7 1892
再見小時候
再見小時候 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

    According to the standard EcmaScript 262. The + and - operators behave differently when strings are involved. The first converts every value to a string. The second converts every value to a number.

    From the standard:

    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)

    This rules implies that if in the expression there is a string value, all values involved in the + operation are converted to a string. In JavaScript when the + operator is used with strings, it concatenates them. This is why console.log("5"+1) returns "51". 1 is converted to a string and then, "5" + "1" are concatenated together.

    Nevertheless, the above rule doesn't apply for the - operator. When you are using a - all values are converted to numbers according to the Standard (see below). Therefore, in this case, "5" is converted to 5 and then 1 is subtracted.

    From the standard:

    5 Let lnum be ToNumber(lval).

    6 Let rnum be ToNumber(rval).


    Operator definition from the standard EcmaScript 262.

    Operator + : http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.1 Operator + definition

    Operator - : http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.2 Operator - definition

提交回复
热议问题