JavaScript 中的 parseInt(string) 和 Number(string) 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4564158/
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
What is the difference between parseInt(string) and Number(string) in JavaScript?
提问by DarkLightA
What is the difference between parseInt(string)
and Number(string)
in JavaScript?
JavaScript 中parseInt(string)
和之间有什么区别Number(string)
?
回答by sjngm
parseInt("123qwe")
returns 123
返回 123
Number("123qwe")
returns NaN
返回 NaN
In other words parseInt()
parses up to the first non-digit and returns whatever it had parsed. Number()
wants to convert the entire string into a number, which can also be a float BTW.
换句话说,parseInt()
解析到第一个非数字并返回它解析的任何内容。Number()
想把整个字符串转换成一个数字,顺便说一句,它也可以是一个浮点数。
EDIT #1: Lucero commented about the radix that can be used along with parseInt()
. As far as that is concerned, please see THE DOCTOR's answerbelow (I'm not going to copy that here, the doc shall have a fair share of the fame...).
编辑 #1:Lucero 评论了可以与parseInt()
. 就此而言,请参阅下面的医生的回答(我不会在这里复制,该医生应该享有相当的名气......)。
EDIT #2: Regarding use cases: That's somewhat written between the lines already. Use Number()
in cases where you indirectly want to check if the given string completely represents a numeric value, float or integer. parseInt()/parseFloat()
aren't that strict as they just parse along and stop when the numeric value stops (radix!), which makes it useful when you need a numeric value at the front "in case there is one" (note that parseInt("hui")
also returns NaN
). And the biggest difference is the use of radix that Number()
doesn't know of and parseInt()
may indirectly guess from the given string (that can cause weird results sometimes).
编辑#2:关于用例:这已经有点写在两行之间了。使用Number()
的情况下,您间接要检查给定的字符串完全代表一个数值,浮点或整数。parseInt()/parseFloat()
不是那么严格,因为它们只是在数值停止时继续解析并停止(基数!),这在您需要前面的数值“以防万一”时非常有用(注意parseInt("hui")
也返回NaN
)。最大的区别是使用了Number()
不知道并且parseInt()
可能从给定字符串间接猜测的基数(有时会导致奇怪的结果)。
回答by THE DOCTOR
The first one takes two parameters:
第一个需要两个参数:
parseInt(string, radix)
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
radix 参数用于指定使用哪种数字系统,例如基数为 16(十六进制)表示字符串中的数字应从十六进制数解析为十进制数。
If the radix parameter is omitted, JavaScript assumes the following:
如果 radix 参数被省略,JavaScript 假定如下:
- If the string begins with "0x", the
radix is 16 (hexadecimal) - If the string begins with "0", the
radix is 8 (octal). This feature
is deprecated - If the string begins with any other value, the radix is 10 (decimal)
- 如果字符串以“0x”开头,则
基数为16(十六进制) - 如果字符串以“0”开头,则基数为 8(八进制)。此功能
已弃用 - 如果字符串以任何其他值开头,则基数为 10(十进制)
The other function you mentioned takes only one parameter:
您提到的另一个函数只需要一个参数:
Number(object)
The Number() function converts the object argument to a number that represents the object's value.
Number() 函数将对象参数转换为表示对象值的数字。
If the value cannot be converted to a legal number, NaN is returned.
如果该值无法转换为合法数字,则返回 NaN。
回答by Steven Keith
parseInt(string)will convert a string containing non-numeric characters to a number, as long as the string begins with numeric characters
parseInt(string)将包含非数字字符的字符串转换为数字,只要字符串以数字字符开头
'10px' => 10
Number(string)will return NaN if the string contains any non-numeric characters
如果字符串包含任何非数字字符,则Number(string)将返回 NaN
'10px' => NaN
回答by ChaosPandion
The parseInt
function allows you to specify a radix for the input string and is limited to integer values.
该parseInt
函数允许您为输入字符串指定基数,并且仅限于整数值。
parseInt('Z', 36) === 35
The Number
constructor called as a function will parse the string with a grammar and is limited to base 10 and base 16.
作为Number
函数调用的构造函数将使用语法解析字符串,并且限制为基数 10 和基数 16。
StringNumericLiteral ::: StrWhiteSpaceopt StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt StrWhiteSpace ::: StrWhiteSpaceChar StrWhiteSpaceopt StrWhiteSpaceChar ::: WhiteSpace LineTerminator StrNumericLiteral ::: StrDecimalLiteral HexIntegerLiteral StrDecimalLiteral ::: StrUnsignedDecimalLiteral + StrUnsignedDecimalLiteral - StrUnsignedDecimalLiteral StrUnsignedDecimalLiteral ::: Infinity DecimalDigits . DecimalDigitsopt ExponentPartopt . DecimalDigits ExponentPartopt DecimalDigits ExponentPartopt DecimalDigits ::: DecimalDigit DecimalDigits DecimalDigit DecimalDigit ::: one of 0 1 2 3 4 5 6 7 8 9 ExponentPart ::: ExponentIndicator SignedInteger ExponentIndicator ::: one of e E SignedInteger ::: DecimalDigits + DecimalDigits - DecimalDigits HexIntegerLiteral ::: 0x HexDigit 0X HexDigit HexIntegerLiteral HexDigit HexDigit ::: one of 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F
回答by dicoder
Addendum to @sjngm's answer:
They both also ignore whitespace:
var foo = " 3 "; console.log(parseInt(foo)); // 3 console.log(Number(foo)); // 3
@sjngm 回答的附录:
他们都忽略了空格:
var foo = " 3 "; console.log(parseInt(foo)); // 3 console.log(Number(foo)); // 3
It is not exactly correct. As sjngmwrote parseInt parses string to first number. It is true. But the problem is when you want to parse number separated with whitespace ie. "12 345". In that case parseInt("12 345")
will return 12
instead of 12345
.
So to avoid that situation you must trim whitespaces before parsing to number.
My solution would be:
这并不完全正确。正如sjngm所写, parseInt 将字符串解析为第一个数字。是真的。但问题是当你想解析用空格分隔的数字时,即。“12 345”。在那种情况下parseInt("12 345")
将返回12
而不是12345
. 因此,为避免这种情况,您必须在解析为 number 之前修剪空格。我的解决方案是:
var number=parseInt("12 345".replace(/\s+/g, ''),10);
Notice one extra thing I used in parseInt() function. parseInt("string",10)
will set the number to decimal format. If you would parse string like "08" you would get 0 because 8 is not a octal number.Explanation is here
请注意我在 parseInt() 函数中使用的另一件事。parseInt("string",10)
将数字设置为十进制格式。如果你解析像 "08" 这样的字符串,你会得到 0,因为8 不是八进制数。说明在这里
回答by Niels Bom
Addendum to @sjngm's answer:
@sjngm 回答的附录:
They both also ignore whitespace:
他们都忽略了空格:
var foo = " 3 ";
console.log(parseInt(foo)); // 3
console.log(Number(foo)); // 3