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.(我刚刚学会了JavaScript认为前导零表示八进制整数的困难方式,并且由于base-8中没有"8"
或"9"
,因此该函数返回零。) Like it or not, this is by design .(无论喜欢与否, 这都是设计的 。)
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.(JavaScript标准的第5版( ECMA-262 )引入了一个突破性的变化,消除了这种行为。) Mozilla has a good write-up .(Mozilla 写得很好。)
ask by Portman translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…