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
执行解析,例如:
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
将忽略与当前使用的基数的任何数字都不对应的尾随字符.
Also parseInt
will ignore trailing characters that don't correspond with any digit of the currently used base.
Number
构造函数不检测隐式八进制,但可以检测显式八进制表示法:
The Number
constructor doesn't detect implicit octals, but can detect the explicit octal notation:
Number("010"); // 10
Number("0o10") // 8, explicit octal
parseInt("010"); // 8, implicit octal
parseInt("010", 10); // 10, decimal radix used
它可以处理十六进制的数字,就像parseInt
:
And it can handle numbers in hexadecimal notation, just like parseInt
:
Number("0xF"); // 15
parseInt("0xF"); //15
此外,一种广泛使用的用于执行数值类型转换的结构是 一元 +
运算符 (p. 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屋!