从DOM中提取数字并使用它们进行计算时,我必须遵循哪条规则? javascript如何知道值是否为数字?我应该一直使用parseInt吗?
给出以下代码:
HTML
<div id="myvalue">5</div>
<div id="withParseInt"></div>
<div id="withoutParseInt"></div>
<div id="withoutParseIntButIncrement"></div>
JS&amp; jQuery的:
var value = $('#myvalue').text();
$('#withParseInt').text(parseInt(value) + 1);
$('#withoutParseInt').text(value + 1);
$('#withoutParseIntButIncrement').text(value++);
提供以下输出:
5
6
51
5
答案 0 :(得分:12)
.text()
方法将始终返回一个字符串。某些运算符(如+
运算符)会被重载以执行算术运算和字符串运算。在字符串的情况下,它执行连接,因此“51”结果。
如果您有一个字符串并且需要使用非强制操作符,则必须使用parseInt
(或其他一些转换为数字的方法)。
但是,*
运算符例如implicity执行此强制,因此在这种情况下您不需要parseInt
调用(例如,请参阅updated fiddle)。
请注意,增量++
运算符确实强制其操作数,但您已使用后缀运算符,因此它不会产生任何影响。使用前缀运算符,您可以看到它正常工作:
$('#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
答案 1 :(得分:7)
唯一的规则:
从DOM检索的每个值都是一个字符串。
答案 2 :(得分:1)
是的,你应该总是使用parseInt()或Number()来保证安全。否则Javascript将决定如何处理它
+
将连接两个字符串-
将计算数值差异答案 3 :(得分:1)
使用parseInt
只是为了安全起见总是好的,特别是因为你可以为数字系统提供第二个参数。
顺便说一句,在你的最后一个例子中,如果你想要它等于6,它应该是++value
。