本文翻译自:What is the difference between parseInt() and Number()?
将字符串转换为数字时, parseInt()
和Number()
行为如何不同?
#1楼
参考:https://stackoom.com/question/HA86/parseInt-和Number-有什么区别
#2楼
If you are looking for performance then probably best results you'll get with bitwise right shift "10">>0
. 如果您正在寻找性能,那么最好按位右移"10">>0
获得最佳结果。 Also multiply ( "10" * 1
) or not not ( ~~"10"
). 还要乘以( "10" * 1
)或不乘( ~~"10"
)。 All of them are much faster of Number
and parseInt
. 所有这些parseInt
Number
和parseInt
快得多。 They even have "feature" returning 0 for not number argument. 他们甚至具有“功能”,而不是数字参数返回0。 Here are Performance tests . 这是性能测试 。
#3楼
I found two links of performance compare among several ways of converting string
to int
. 我发现在将string
转换为int
几种方法中,比较了性能的两个链接。
parseInt(str,10)
parseFloat(str)
str << 0
+str
str*1
str-0
Number(str)
http://jsben.ch/#/zGJHM http://jsben.ch/#/zGJHM
http://phrogz.net/js/string_to_number.html http://phrogz.net/js/string_to_number.html
#4楼
我一直使用parseInt,但是要注意前导零会迫使它进入八进制模式。
#5楼
typeof parseInt("123") => number
typeof Number("123") => number
typeof new Number("123") => object (Number primitive wrapper object)
first two will give you better performance as it returns a primitive instead of an object. 前两个会返回原始值而不是对象,因此会提高性能。
#6楼
Well, they are semantically different , the Number
constructor called as a function performs type conversion and parseInt
performs parsing , eg: 嗯,它们在语义上是不同的 , 称为函数的Number
构造函数执行类型转换 , parseInt
执行解析 ,例如:
// parsing:
parseInt("20px"); // 20
parseInt("10100", 2); // 20
parseInt("2e1"); // 2
// type conversion
Number("20px"); // NaN
Number("2e1"); // 20, exponential notation
Keep in mind that if parseInt
detects a leading zero on the string, it will parse the number in octal base, this has changed on ECMAScript 5, the new version of the standard, but it will take a long time to get in browser implementations (it's an incompatibility with ECMAScript 3), also parseInt
will ignore trailing characters that don't correspond with any digit of the currently used base. 请记住,如果parseInt
在字符串上检测到前导零,则它将以八进制为基础解析数字,这在标准的新版本ECMAScript 5中已更改,但是要花很长时间才能进入浏览器实现( (与ECMAScript 3不兼容), parseInt
也会忽略与当前使用的基数不匹配的尾随字符。
The Number
constructor doesn't detect octals: Number
构造函数不检测八进制:
Number("010"); // 10
parseInt("010"); // 8, implicit octal
parseInt("010", 10); // 10, decimal radix used
But it can handle numbers in hexadecimal notation, just like parseInt
: 但是它可以以十六进制表示法处理数字,就像parseInt
一样:
Number("0xF"); // 15
parseInt("0xF"); //15
In addition, a widely used construct to perform Numeric type conversion, is the Unary +
Operator (p. 72) , it is equivalent to using the Number
constructor as a function: 另外,用于执行数值类型转换的一种广泛使用的构造是Unary +
运算符(p。72) ,它等效于将Number
构造函数用作函数:
+"2e1"; // 20
+"0xF"; // 15
+"010"; // 10