您认为parseInt("08")将返回什么? [英] What do you think parseInt("08") will return?
问题描述
Possible Duplicate:
Workarounds for JavaScript parseInt octal bug
令人惊讶的是,它返回0
.为什么?什么是获得正确结果的(正确)解决方案?
Surprisingly it returns 0
. Why? and what's the (proper) solution to get correct results?
推荐答案
使用基数:
var x = parseInt("08", 10);
某些JavaScript实现将第三个数字系统添加到标准定义的两个数字系统中(十进制,默认值;十六进制,以0x
前缀):八进制,以0
前缀.这是非标准,但在最新规格.
Some JavaScript implementations add a third numeral system to the two defined by the standard (decimal, the default; and hex, prefixed with 0x
): Octal, prefixed with 0
. This is non-standard but acknowledged as common in the latest spec.
由于8
不是有效的八进制数字,所以parseInt
在那里停止,并返回值0
.
Since 8
is not a valid octal digit, parseInt
stops there, returning the value 0
.
通过显式使用基数,您告诉parseInt
不要试图弄清楚正在使用的数字系统,而是使用您指定的数字系统.输入parseInt
时的直觉应该总是 指定基数.如果不这样做,您就会变得陌生.
By explicitly using a radix, you tell parseInt
not to try to figure out what numeral system is being used but instead to use the one you specify. Your instinct when typing parseInt
should always be to specify the radix; not doing so leaves you open to oddities.
这篇关于您认为parseInt("08")将返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!