num++;在javascript中
但是num++;在javascript中,javascript,Javascript,但是 为什么?因为+运算符也用于字符串连接 var num = "1"; num++; //Gives 2. Javascript是一种弱类型语言,因此它对类型转换更为宽松 您案例中使用的++运算符是后缀增量运算符,它只对数字进行操作,因此它的作用与您预期的一样: var num = "1"; // The 1 is converted to a string then concatenated with "1" to make "11". num = num+1; 要提示应该进行加法,
为什么?因为
+
运算符也用于字符串连接
var num = "1";
num++; //Gives 2.
Javascript是一种弱类型语言,因此它对类型转换更为宽松
您案例中使用的++
运算符是后缀增量运算符,它只对数字进行操作,因此它的作用与您预期的一样:
var num = "1";
// The 1 is converted to a string then concatenated with "1" to make "11".
num = num+1;
要提示应该进行加法,请减去零:
var num = "1";
// num is converted to a number then incremented.
num++;
或者使用一元+
运算符:
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;
因为++是一个数值运算,所以
num
是从字符串中强制转换的,然后该运算发生
但是,+
既可以用于数字操作数(add),也可以用于字符串操作数(串联)。因此,1
被转换为字符串,然后与1
连接,从而得到11
var num = "1";
// The unary + operator also forces num to be converted to an actual number
num = (+num) + 1;
第一个是,+运算符是字符串连接。这样就得到了连接结果
var num = "1";
num = num+1; //Gives "11"
第二个是,++运算符是后增量运算符。所以你得到了额外的结果
如果您希望更改+运算符以进行添加。像这样使用
var num = "1";
num++; //Gives 2.
函数的作用是:解析字符串并返回整数。因此它返回整数值。实际上,您将字符串存储在num变量中,并与num连接。 为了存储数字,在将数字存储到num变量中时,必须删除1周围的引号 var-num=1; num=num+1 现在结果将是2而不是1
var num = "1";
num++; //Gives 2.
var num = "1";
num = parseInt(num)+1; //Gives "2"