何时使用parseInt

iap*_*dev 14 javascript jquery parseint

从DOM中提取数字并使用它们进行计算时,我必须遵循哪条规则?javascript如何知道值是否为数字?我应该总是使用parseInt吗?

鉴于以下代码:

HTML

<div id="myvalue">5</div>
<div id="withParseInt"></div>
<div id="withoutParseInt"></div>
<div id="withoutParseIntButIncrement"></div>
Run Code Online (Sandbox Code Playgroud)

JS和jQuery:

var value = $('#myvalue').text();
$('#withParseInt').text(parseInt(value) + 1);
$('#withoutParseInt').text(value + 1);
$('#withoutParseIntButIncrement').text(value++);
Run Code Online (Sandbox Code Playgroud)

给出以下输出:

5
6
51
5
Run Code Online (Sandbox Code Playgroud)

小提琴:http://jsfiddle.net/ytxKU/3/

Jam*_*ice 12

.text()方法将始终返回一个字符串.某些运算符(如+运算符)会重载以执行算术运算和字符串运算.在字符串的情况下,它执行连接,因此"51"结果.

如果您有一个字符串并且需要使用非强制运算符,则必须使用parseInt(或其他一些转换为数字的方法).

然而,*例如隐含的运算符执行这种强制,因此parseInt在那种情况下你不需要调用(例如,参见更新的小提琴).

请注意,增量++运算符强制其操作数,但您已使用后缀运算符,因此它不会产生任何影响.使用前缀运算符,您可以看到它工作:

$('#withoutParseIntButIncrement').text(++value);
Run Code Online (Sandbox Code Playgroud)

所以,总结一下:

// 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);
Run Code Online (Sandbox Code Playgroud)

旁注:总是将第二个参数(基数)传递给,这被认为是一种好习惯parseInt.这可以确保在正确的基数中解析数字:

parseInt(value, 10); // For base 10
Run Code Online (Sandbox Code Playgroud)


Amb*_*mps 7

唯一的规则:

您从DOM检索的每个值都是一个字符串.

  • ...并且您插入DOM的每个值都成为一个字符串. (4认同)