带有前导零的Javascript parseInt()

问题描述:

Javascript的parseInt函数似乎不能完全正常工作。

Javascript's parseInt function does not seem to completely work.

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

你无法解释。 试一试。 (jsFiddle)

编辑由于此问题已被询问和回答,因此不推荐使用默认为八进制基数的功能 。 [ 1 ] [ 2 ]

Edit Since this question was asked and answered, the "feature" of defaulting to octal radix has been deprecated. [1] [2]

这是因为如果数字以'0'开头,则将其视为基数8(八进制)。

This is because if a number starts with a '0', it's treated as base 8 (octal).

您可以通过将基数作为第2个来强制基数参数。

You can force the base by passing the base as the 2nd parameter.

parseInt("09", 10) // 9

根据文档,第二个参数是可选的,但它的并不总是假设为10,正如您从示例中看到的那样。

According to the docs, the 2nd parameter is optional, but it's not always assumed to be 10, as you can see from your example.