javascript parseInt("08") 返回 0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12318830/
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
parseInt("08") returns 0
提问by Curt
Possible Duplicate:
Workarounds for JavaScript parseInt octal bug
I've been working on a javascript function, setting date objects by declaring the year, month & date. However, when the month has a value of 08
or 09
, 0
is returned when using parseInt()
. See below:
我一直在研究 javascript 函数,通过声明年、月和日期来设置日期对象。然而,当该月的值08
或者09
,0
使用时返回parseInt()
。见下文:
parseInt("01") //returns 1
parseInt("02") //returns 2
parseInt("03") //returns 3
parseInt("04") //returns 4
parseInt("05") //returns 5
parseInt("06") //returns 6
parseInt("07") //returns 7
parseInt("08") //returns 0?
parseInt("09") //returns 0?
parseInt("10") //returns 10
I've created a jsFiddle to demonstrate this issue:
我创建了一个 jsFiddle 来演示这个问题:
Why does parseInt("08")
and parseInt("09")
return 0
?
为什么parseInt("08")
和parseInt("09")
返回0
?
回答by zerkms
That's because numbers started with 0 are considered to be octal. And 08 is a wrong number in octal.
那是因为以 0 开头的数字被认为是八进制的。08 是八进制的错误数字。
Use parseInt('09', 10);
instead.
使用parseInt('09', 10);
来代替。
回答by Some Guy
It's being parsed as an octal number. Use the radix
parameter in parseInt
.
它被解析为八进制数。使用中的radix
参数parseInt
。
parseInt('08', 10);
parseInt('08', 10);
An update: As of ES5, browsers should nothave this bug. Octal literals require to be in the form 0o12
to be considered Octal numbers. 08
by default is now considered a decimal number in ES5, however, all browsers may not support this yet, so you should continue to pass the radix
parameter to parseInt
更新:由于ES5的,浏览器应该不会有这样的错误。八进制文字需要采用0o12
被视为八进制数的形式。08
默认情况下,在 ES5 中现在被认为是十进制数,但是,所有浏览器可能还不支持这一点,因此您应该继续将radix
参数传递给parseInt
回答by Paddy
You can fix this by including the radix, e.g.:
您可以通过包含基数来解决此问题,例如:
parseInt("08", 10); // outputs 8
回答by Sepster
You need to add a radix of ten:
您需要添加 10 的基数:
parseInt("08", 10);
Some implementations default to octal.
一些实现默认为八进制。