parseInt()和Number()之间有什么区别?(What is the difference between parseInt() and Number()?)

编程入门 行业动态 更新时间:2024-10-28 13:15:54
parseInt()和Number()之间有什么区别?(What is the difference between parseInt() and Number()?)

将字符串转换为数字时, 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"; // 10

Well, 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 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.

The Number constructor doesn't detect octals:

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:

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:

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

更多推荐

本文发布于:2023-08-07 20:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465799.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   parseInt   Number   difference

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!