Javascript parseInt() 和 Number() 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4090518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:34:03  来源:igfitidea点击:

What is the difference between parseInt() and Number()?

javascriptperformance

提问by Mark

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

如何parseInt()以及Number()将字符串转换为数字时不同的表现?

回答by CMS

Well, they are semantically different, the Numberconstructor called as a functionperforms type conversionand parseIntperforms parsing, e.g.:

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

// 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 parseIntdetects 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 parseIntwill ignore trailing characters that don't correspond with any digit of the currently used base.

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

The Numberconstructor doesn't detect octals:

Number构造函数不检测八进制:

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:

但它可以处理十六进制表示法的数字,就像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 Numberconstructor as a function:

此外,一个广泛使用的用于执行数值类型转换的构造是一元+运算符 (p. 72),它等效于将Number构造函数用作函数:

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

回答by letronje

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

first two will give you better performance as it returns a primitive instead of an object.

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

回答by Saulius

If you are looking for performance then probably best results you'll get with bitwise right shift "10">>0. Also multiply ("10" * 1) or not not (~~"10"). All of them are much faster of Numberand parseInt. They even have "feature" returning 0 for not number argument. Here are Performance tests.

如果您正在寻找性能,那么按位右移可能会获得最佳结果"10">>0。也乘("10" * 1)或不乘(~~"10")。所有这些都比Number和快得多parseInt。他们甚至有“功能”为非数字参数返回 0。这里是性能测试

回答by zangw

I found two links of performance compare among several ways of converting stringto int.

我发现在几种转换stringint.

parseInt(str,10)    
parseFloat(str)
str << 0
+str
str*1 
str-0
Number(str)

http://jsben.ch/#/zGJHM

http://jsben.ch/#/zGJHM

http://phrogz.net/js/string_to_number.html

http://phrogz.net/js/string_to_number.html

回答by Naeem Shaikh

One minor difference is what they convert of undefinedor null,

一个微小的区别是他们转换的内容undefinedor null

Number() Or Number(null) // returns 0

while

尽管

parseInt() Or parseInt(null) // returns NaN

回答by Diodeus - James MacFarlane

I always use parseInt, but beware of leading zeroes that will force it into octalmode.

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

回答by Willem van der Veen

Summary:

概括:

parseInt():

parseInt()

  • Takes a string as a first argument, the radix (An integer which is the base of a numeral system e.g. decimal 10 or binary 2) as a second argument
  • The function returns a integer number, if the first character cannot be converted to a number NaNwill be returned.
  • If the parseInt()function encounters a non numerical value, it will cut off the rest of input string and only parse the part until the non numerical value.
  • If the radix is undefinedor 0, JS will assume the following:
    • If the input string begins with "0x" or "0X", the radix is 16 (hexadecimal), the remainder of the string is parsed into a number.
    • If the input value begins with a 0 the radix can be either 8 (octal) or 10 (decimal). Which radix is chosen is depending on JS engine implementation. ES5specifies that 10 should be used then. However, this is not supported by all browsers, therefore always specify radix if your numbers can begin with a 0.
    • If the input value begins with any number, the radix will be 10
  • 将字符串作为第一个参数,基数(作为数字系统基础的整数,例如十进制 10 或二进制 2)作为第二个参数
  • 该函数返回一个整数,如果第一个字符不能转换为数字NaN将返回。
  • 如果parseInt()函数遇到非数值,它会切断输入字符串的其余部分,只解析部分直到非数值。
  • 如果基数为undefined或 0,JS 将假设如下:
    • 如果输入字符串以“0x”或“0X”开头,基数为16(十六进制),则将字符串的其余部分解析为数字。
    • 如果输入值以 0 开头,则基数可以是 8(八进制)或 10(十进制)。选择哪个基数取决于 JS 引擎的实现。ES5指定应该使用 10。但是,并非所有浏览器都支持此功能,因此如果您的数字可以以 0 开头,请始终指定基数。
    • 如果输入值以任何数字开头,则基数将为 10

Number():

Number()

  • The Number()constructor can convert any argument input into a number. If the Number()constructor cannot convert the input into a number, NaNwill be returned.
  • The Number()constructor can also handle hexadecimal number, they have to start with 0x.
  • Number()构造可以任何参数输入转换成一个数字。如果Number()构造函数无法将输入转换为数字,NaN则返回。
  • Number()构造还可以处理十六进制数,他们必须开始0x

Example:

例子:

console.log(parseInt('0xF', 16));  // 15

// z is no number, it will only evaluate 0xF, therefore 15 is logged
console.log(parseInt('0xFz123', 16));

// because the radix is 10, A is considered a letter not a number (like in Hexadecimal)
// Therefore, A will be cut off the string and 10 is logged
console.log(parseInt('10A', 10));  // 10

// first character isnot a number, therefore parseInt will return NaN
console.log(parseInt('a1213', 10));


console.log('\n');


// start with 0X, therefore Number will interpret it as a hexadecimal value
console.log(Number('0x11'));

// Cannot be converted to a number, NaN will be returned, notice that
// the number constructor will not cut off a non number part like parseInt does
console.log(Number('123A'));

// scientific notation is allowed
console.log(Number('152e-1'));  // 15.21

回答by Atishay Baid

parseInt()-> Parses a number to specified redix.

parseInt()-> 将数字解析为指定的 redix。

Number()-> Converts the specified value to its numeric equivalent or NaN if it fails to do so.

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

Hence for converting some non-numeric value to number we should always use Number() function.

因此,要将一些非数字值转换为数字,我们应该始终使用 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

There are various corner case to parseInt()functions as it does redix conversion, hence we should avoid using parseInt() function for coersion purposes.

parseInt()在进行 redix 转换时,函数有各种极端情况,因此我们应该避免使用 parseInt() 函数来进行强制转换。

Now, to check weather the provided value is Numeric or not,we should use nativeisNaN()function

现在,要检查天气提供的值是否为数字,我们应该使用本机isNaN()函数

回答by Johan Rylander

parseInt converts to a integer number, that is, it strips decimals. Number does not convert to integer.

parseInt 转换为整数,即去除小数。数字不会转换为整数。

回答by kagronick

Its a good idea to stay away from parseInt and use Number and Math.round unless you need hex or octal. Both can use strings. Why stay away from it?

远离 parseInt 并使用 Number 和 Math.round 是个好主意,除非您需要十六进制或八进制。两者都可以使用字符串。为什么要远离它?

parseInt(0.001, 10)
0

parseInt(-0.0000000001, 10)
-1

parseInt(0.0000000001, 10)
1

parseInt(4000000000000000000000, 10)
4

It completly butchers really large or really small numbers. Oddly enough it works normally if these inputs are a string.

它完全屠宰非常大或非常小的数字。奇怪的是,如果这些输入是字符串,它可以正常工作。

parseInt("-0.0000000001", 10)
0

parseInt("0.0000000001", 10)
0

parseInt("4000000000000000000000", 10)
4e+21

Instead of risking hard to find bugs with this and the other gotchas people mentioned, I would just avoid parseInt unless you need to parse something other than base 10. Number, Math.round, Math.foor, and .toFixed(0) can all do the same things parseInt can be used for without having these types of bugs.

与其冒着很难找到错误以及人们提到的其他问题的风险,我只会避免使用 parseInt,除非您需要解析除基数 10 以外的其他内容。 Number、Math.round、Math.foor 和 .toFixed(0) 都可以做同样的事情 parseInt 可以用于没有这些类型的错误。

If you really want or need to use parseInt for some of it's other qualities, never use it to convert floats to ints.

如果你真的想要或需要使用 parseInt 来实现它的一些其他特性,永远不要使用它来将浮点数转换为整数。