parseInt vs一元加,什么时候使用? [英] parseInt vs unary plus, when to use which?
问题描述
此行之间有什么区别:
var a = parseInt("1", 10); // a === 1
和这一行
var a = +"1"; // a === 1
此 jsperf测试显示,在当前的chrome版本中,一元运算符要快得多,假设它是用于node.js!?
This jsperf test shows that the unary operator is much faster in the current chrome version, assuming it is for node.js!?
如果我尝试转换不是数字的字符串,都返回NaN
:
If I try to convert strings which are not numbers both return NaN
:
var b = parseInt("test" 10); // b === NaN
var b = +"test"; // b === NaN
所以我什么时候应该更喜欢使用parseInt
而不是一元加号(尤其是在node.js中)?
So when should I prefer using parseInt
over the unary plus (especially in node.js)???
编辑:和双波浪号运算符~~
有什么区别?
edit: and what's the difference to the double tilde operator ~~
?
推荐答案
#请参阅此答案以获取更完整的信息案件集
#Please see this answer for a more complete set of cases
嗯,这是我所知道的一些区别:
Well, here are a few differences I know of:
-
空字符串
""
评估为0
,而parseInt
评估为NaN
. IMO,空白字符串应为NaN
.
An empty string
""
evaluates to a0
, whileparseInt
evaluates it toNaN
. IMO, a blank string should be aNaN
.
+'' === 0; //true
isNaN(parseInt('',10)); //true
一元+
的行为更像parseFloat
,因为它也接受小数.
The unary +
acts more like parseFloat
since it also accepts decimals.
parseInt
看到非数字字符(例如要用作小数点.
的句点)时,它将停止解析.
parseInt
on the other hand stops parsing when it sees a non-numerical character, like the period that is intended to be a decimal point .
.
+'2.3' === 2.3; //true
parseInt('2.3',10) === 2; //true
parseInt
和parseFloat
解析并构建字符串从左到右.如果他们看到一个无效字符,它将返回已解析的内容(如果有)为数字,如果没有解析为数字,则返回NaN
.
parseInt
and parseFloat
parses and builds the string left to right. If they see an invalid character, it returns what has been parsed (if any) as a number, and NaN
if none was parsed as a number.
如果整个字符串不可转换为数字,则一元+
将返回NaN
.
The unary +
on the other hand will return NaN
if the entire string is non-convertible to a number.
parseInt('2a',10) === 2; //true
parseFloat('2a') === 2; //true
isNaN(+'2a'); //true
如 @Alex K. 的注释所示,parseInt
和parseFloat
将按字符进行解析.这意味着十六进制和指数符号将失败,因为x
和e
被视为非数字组件(至少在base10上).
As seen in the comment of @Alex K., parseInt
and parseFloat
will parse by character. This means hex and exponent notations will fail since the x
and e
are treated as non-numerical components (at least on base10).
一元+
会正确转换它们.
parseInt('2e3',10) === 2; //true. This is supposed to be 2000
+'2e3' === 2000; //true. This one's correct.
parseInt("0xf", 10) === 0; //true. This is supposed to be 15
+'0xf' === 15; //true. This one's correct.
这篇关于parseInt vs一元加,什么时候使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!