作者:ekuuu | 来源:互联网 | 2023-08-22 16:31
TryexecutingthefollowinginJavaScript:尝试在JavaScript中执行以下操作:parseInt(01);equals1parseIn
Try executing the following in Javascript:
尝试在Javascript中执行以下操作:
parseInt('01'); //equals 1
parseInt('02'); //equals 2
parseInt('03'); //equals 3
parseInt('04'); //equals 4
parseInt('05'); //equals 5
parseInt('06'); //equals 6
parseInt('07'); //equals 7
parseInt('08'); //equals 0 !!
parseInt('09'); //equals 0 !!
I just learned the hard way that Javascript thinks the leading zero indicates an octal integer, and since there is no "8"
or "9"
in base-8, the function returns zero. Like it or not, this is by design.
我刚学到了Javascript认为前导零表示八进制整数,因为在base-8中没有“8”或“9”,函数返回零。不管你喜不喜欢,这都是由设计决定的。
What are the workarounds?
解决方法是什么?
Note: For sake of completeness, I'm about to post a solution, but it's a solution that I hate, so please post other/better answers.
注意:为了完整性起见,我将发布一个解决方案,但它是我讨厌的解决方案,所以请发布其他/更好的答案。
Update:
更新:
The 5th Edition of the Javascript standard (ECMA-262) introduces a breaking change that eliminates this behavior. Mozilla has a good write-up.
第5版的Javascript标准(ECMA-262)引入了一个可以消除这种行为的中断更改。Mozilla有一个不错的记录。
9 个解决方案