Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

javascript - 我如何解决JavaScript的parseInt八进制行为?(How do I work around JavaScript's parseInt octal behavior?)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is a common Javascript gotcha with a simple solution:(这是一个常见的Javascript问题,有一个简单的解决方案:)

Just specify the base , or 'radix', like so:(只需指定基数或“基数”,如下所示:) parseInt('08',10); // 8 You could also use Number :(你也可以使用数字 :) Number('08'); // 8

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...