在将字符串转换为数字时,parseInt()和Number()的行为如何不同?


当前回答

如果你正在寻找性能,那么最好的结果可能是按位右移“10”>>0。也可以乘(“10”* 1)或not not(~~“10”)。它们都比Number和parseInt快得多。 他们甚至有“feature”为非数字参数返回0。 下面是性能测试。

其他回答

我总是使用parseInt,但要注意前导零会迫使它进入八进制模式。

parseInt转换为整数,也就是说,它去掉小数。数字不转换为整数。

typeof parseInt("123") => number
typeof Number("123") => number
typeof new Number("123") => object (Number primitive wrapper object)

前两个将提供更好的性能,因为它返回一个原语而不是一个对象。

parseInt() ->解析一个数字到指定的redix。

Number()->如果转换失败,则将指定值转换为其等效数值或NaN。

因此,要将一些非数字值转换为数字,我们应该始终使用number()函数。

eg.

Number("")//0
parseInt("")//NaN

Number("123")//123
parseInt("123")//123

Number("123ac") //NaN,as it is a non numeric string
parsInt("123ac") //123,it parse decimal number outof string

Number(true)//1
parseInt(true) //NaN

parseInt()函数有各种各样的极端情况,因为它进行重定向转换,因此我们应该避免使用parseInt()函数进行强制转换。

现在,要检查所提供的值是否是Numeric,我们应该使用nativeisNaN()函数

嗯,它们在语义上是不同的,作为函数调用的Number构造函数执行类型转换,而parseInt执行解析,例如:

// parsing:
parseInt("20px");       // 20
parseInt("10100", 2);   // 20
parseInt("2e1");        // 2

// type conversion
Number("20px");       // NaN
Number("2e1");        // 20, exponential notation

此外,parseInt将忽略与当前使用的基数中任何数字不对应的尾随字符。

Number构造函数不检测隐式八进制,但可以检测显式八进制符号:

Number("010");         // 10
Number("0o10")         // 8, explicit octal

parseInt("010");       // 8, implicit octal
parseInt("010", 10);   // 10, decimal radix used

它可以处理十六进制的数字,就像parseInt一样:

Number("0xF");   // 15
parseInt("0xF"); //15

此外,用于执行Numeric类型转换的一个广泛使用的构造是Unary + Operator(第72页),它相当于将Number构造函数用作函数:

+"2e1";   // 20
+"0xF";   // 15
+"010";   // 10