从 DOM 中提取数字并用它们计算时,我必须遵循什么规则? javascript 如何知道一个值是不是数字?我应该始终使用 parseInt 吗?
给定以下代码:
HTML
<div id="myvalue">5</div>
<div id="withParseInt"></div>
<div id="withoutParseInt"></div>
<div id="withoutParseIntButIncrement"></div>
JS 和 jQuery:
var value = $('#myvalue').text();
$('#withParseInt').text(parseInt(value) + 1);
$('#withoutParseInt').text(value + 1);
$('#withoutParseIntButIncrement').text(value++);
给出以下输出:
5
6
51
5
fiddle :http://jsfiddle.net/ytxKU/3/
最佳答案
.text()
方法总是返回一个字符串。一些运算符,如 +
运算符,被重载以执行算术和字符串运算。对于字符串,它执行连接,因此结果为“51”。
如果您有一个字符串并且需要使用非强制运算符,则必须使用 parseInt
(或其他一些转换为数字的方法)。
但是,例如 *
运算符会隐式执行此强制转换,因此在那种情况下您不需要 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
关于javascript - 何时使用 parseInt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15429418/