問題:
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 寫得很好。
解決方案:
參考一: https://stackoom.com/question/3ZDB參考二: How do I work around JavaScript's parseInt octal behavior?