简体   繁体   中英

Why does the radix for JavaScript's parseInt default to 8?

在JavaScript的parseInt函数中将基数默认为8(如果字符串以0开头)让我烦恼,只因为我继续忘记将可选的第二个参数传递为10.我正在寻找答案告诉我为什么它有意义默认为8。

It only "defaults" to 8 if the input string starts with 0. This is an unfortunate carryover from C and C++.

You can use Number('0123') instead, or, as you said in the question, parseInt('0123', 10) .

How do I work around JavaScript's parseInt octal behavior?


Can you tell me more about this carryover?


Note: ECMAScript strict mode removes octal syntax.

If a number starts with 0 and contains digits between (and inclusive) 0 to 7, it is interpreted as an octal number (with base 8 instead of 10).

In parseInt however, if a string starts with a 0 it's always interpeted as an octal, and stops searching when it encounters an invalid character (eg the digits 8 or 9 or a character like z ).

parseInt("070");     //56
parseInt("70");      //70
parseInt("070", 10); //70
parseInt("78");      //78
parseInt("078");     //7, because it stops before 8

If you need to convert a string into a number, and you're sure that it contains no invalid characters or fractional parts, you can multiply it with 1 to make a number of it:

1 * "070";           //70

I personally prefer this approach, and believe it's faster than calling functions.

Now, a couple of years later, parseInt() seems to work fine with numbers starting with 0 . Current browsers:

parseInt("019"); // 19 on Firefox 67
parseInt("019"); // 19 on Chrome 75
parseInt("019"); // 19 on Safari 12
parseInt("019"); // 19 on IE 11
parseInt("019"); // 19 on Edge 42

But still, this "fix" must break older scripts that rely on parseInt("019") returning 1 or 0 instead of 19 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM