parseInt()和Number()有什么区别? [英] What is the difference between parseInt() and Number()?

查看:94
本文介绍了parseInt()和Number()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何 parseInt( ) Number() 将字符串转换为数字时的行为会有所不同?

How do parseInt() and Number() behave differently when converting strings to numbers?

推荐答案

嗯,他们在语义上不同 数字被称为函数的构造函数执行类型转换 parseInt 执行解析,例如:

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

请记住,如果 parseInt 检测到字符串的前导零,它将解析八进制数中的数字,这已经在ECMAScript 5(标准的新版本)上发生了变化,但是它需要很长时间才能进入浏览器实现(这是一个与ECMAScript 3)不兼容,同样 parseInt 将忽略与当前使用的基数的任何数字不对应的尾随字符。

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.

Number 构造函数未检测到octals:

The Number constructor doesn't detect octals:

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

但它可以用十六进制表示法处理数字,就像 parseInt

But it can handle numbers in hexadecimal notation, just like parseInt:

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

此外,一个广泛使用的构造来执行数值类型转换,是一元 + 运营商(第72页),它相当于使用 Number 构造函数作为函数:

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

这篇关于parseInt()和Number()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆