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

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

    There is no dedicated string concatenation operator in JavaScript**. The addition operator + performs either string concatenation or addition, depending on the type of operands:

    "1" +  1  // "11"
     1  + "1" // "11"
     1  +  1  // 2
    

    There is no opposite of concatenation (I think) and the subtraction operator - only performs subtraction regardless of the type of operands:

    "1" -  1  // 0
     1  - "1" // 0
     1  -  1  // 0
    "a" -  1  // NaN
    

    ** The . operator in PHP and & operator in VB are dedicated string concatenation operators.

提交回复
热议问题