开发者

What do you think parseInt("08") will return? [duplicate]

This question already has answers here: Clos开发者_如何学运维ed 11 years ago.

Possible Duplicate:

Workarounds for JavaScript parseInt octal bug

Surprisingly it returns 0. Why? and what's the (proper) solution to get correct results?


Use a radix:

var x = parseInt("08", 10);

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.

Since 8 is not a valid octal digit, parseInt stops there, returning the value 0.

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.


"08" mean 8 based number. You should specify second argument.

 parseInt("08", 10)


@T.J. gave a great explanation for the behaviour you see. Another way to parse a number string is to use unary +:

var num = +"08";


From http://www.bennadel.com/blog/2012-Exploring-Javascript-s-parseInt-And-parseFloat-Functions.htm:

Strings that start with "0" are assumed to be base8 (octal).


From MDC - parseInt:

If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.

And the example:

parseInt("08"); // 0, '8' is not an octal digit.

That is, since no radix was passed in and the string begins with 0 octal is assumed. Since 8 is not an octal digit it cannot be parsed.

Solution? Always provide a radix parameter:

parseInt("08", 10);


If you run it through jslint, it'll squawk at you for not including the radix parameter. Yes, the radix is optional, but probably should be included every time. A number starting with 0 is assumed to be octal unless otherwise specified.

var foo = parseInt("08", 10);


Number prefixed with "0" is octal number. 8 is invalid octal number. so the result is 0

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜