将字符串转换为数字时, parseInt()和Number()行为如何不同?
How do parseInt() and Number() behave differently when converting strings to numbers?
最满意答案
那么它们在语义上是不同的 , 作为函数调用的Number构造函数执行类型转换 , parseInt执行解析 ,例如:
// parsing: parseInt("20px"); // 20 parseInt("10100", 2); // 20 parseInt("2e1"); // 2 // type conversion Number("20px"); // NaN Number("2e1"); // 20, exponential notation请记住,如果parseInt检测到字符串上的前导零,它将解析八进制数的基数,这在ECMAScript 5(新版本的标准)上已经更改,但是需要很长时间才能进入浏览器实现它与ECMAScript 3不兼容), parseInt也将忽略与当前使用的基数的任何数字不对应的尾随字符。
Number构造函数不检测八进制:
Number("010"); // 10 parseInt("010"); // 8, implicit octal parseInt("010", 10); // 10, decimal radix used但是它可以处理十六进制符号的数字,就像parseInt :
Number("0xF"); // 15 parseInt("0xF"); //15另外,一个广泛使用的进行数值类型转换的结构是Unary + Operator(第72页) ,它相当于使用Number构造函数作为一个函数:
+"2e1"; // 20 +"0xF"; // 15 +"010"; // 10Well, they are semantically different, the Number constructor called as a function performs type conversion and parseInt performs parsing, e.g.:
// parsing: parseInt("20px"); // 20 parseInt("10100", 2); // 20 parseInt("2e1"); // 2 // type conversion Number("20px"); // NaN Number("2e1"); // 20, exponential notationKeep 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.
The Number constructor doesn't detect octals:
Number("010"); // 10 parseInt("010"); // 8, implicit octal parseInt("010", 10); // 10, decimal radix usedBut it can handle numbers in hexadecimal notation, just like parseInt:
Number("0xF"); // 15 parseInt("0xF"); //15In 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:
+"2e1"; // 20 +"0xF"; // 15 +"010"; // 10更多推荐
发布评论