.text()
方法总是返回一个字符串。一些运算符,比如 +
运算符被重载了用于执行算术和字符串操作。在字符串的情况下,它执行拼接,因此得到了 "51" 的结果。
如果你有一个字符串并需要使用一个不进行强制转换的运算符,你将不得不使用 parseInt
(或其他一些将其转换为数字的方法)。
然而,例如乘法运算符 *
隐式地执行这个类型转换,因此在那种情况下就不需要使用 parseInt
调用(可以查看更新的样例代码)。
请注意,递增运算符 ++
确实对其操作数进行强制转换,但你使用了后缀运算符,所以它不会产生任何效果。使用前缀运算符,你就可以看到它的作用:
$('#withoutParseIntButIncrement').text(++value);
因此,总结一下:
// Parses string to number and adds 1
$('#withParseInt').text(parseInt(value) + 1);
// Coerces number 1 to string "1" and concatenates
$('#withoutParseInt').text(value + 1);
// Implicity coerces string to number, but after it's been inserted into the DOM
$('#withoutParseIntButIncrement').text(value++);
// Implicity coerces string to number, before it's been inserted into the DOM
$('#withoutParseIntButIncrement').text(++value);
// Implicity coerces to number
$('#withoutParseIntButMultiply').text(value * 2);
顺带一提:始终将第二个参数(基数)传递给parseInt
被认为是良好的实践。这可以确保以正确的进制解析数字:
parseInt(value, 10); // For base 10