javascript中的num ++

alt*_*ter 2 javascript

var num = "1";
num = num+1; //Gives "11"
Run Code Online (Sandbox Code Playgroud)

 var num = "1";
 num++; //Gives 2.
Run Code Online (Sandbox Code Playgroud)

为什么?

In *_*ico 5

因为+运算符也用于字符串连接.

var num = "1";
// The 1 is converted to a string then concatenated with "1" to make "11".
num = num+1;
Run Code Online (Sandbox Code Playgroud)

Javascript是一种弱类型语言,因此对类型转换更加宽松.

++在您的情况下使用的运算符是后缀增量运算符,它仅对数字进行操作,因此它按预期运行:

var num = "1";
// num is converted to a number then incremented.
num++;
Run Code Online (Sandbox Code Playgroud)

要提示应该进行添加,减去零:

var num = "1";
// Subtraction operates only on numbers, so it forces num to be converted to an
// actual number so we can properly add 1 to it
num = (num - 0) + 1;
Run Code Online (Sandbox Code Playgroud)

或者使用一元运算+符:

var num = "1";
// The unary + operator also forces num to be converted to an actual number
num = (+num) + 1;
Run Code Online (Sandbox Code Playgroud)