Why JavaScript Treats Leading-Zero Numbers as Octals
In JavaScript, numbers beginning with a leading zero are interpreted as octal numbers (base 8). This behavior originates from an optional extension in ECMAScript 3 that allowed for leading zeros in octal literals.
The LegacyOctalIntegerLiteral Conversion
However, this extension was forbidden in strict mode in ECMAScript 5. As a result, numbers with leading zeros in strict mode code are treated as decimal literals and result in errors.
In non-strict mode, implementation-specific behavior determines how numbers with leading zeros are handled. Some browsers may still interpret them as octal literals, while others may raise errors.
Preventing Octal Interpretation
To ensure that numbers are parsed correctly in base 10, there are two methods:
1. Remove Leading Zeros
Simply remove the leading zero from the number before assigning it, as shown below:
<code class="javascript">var x = 10; // Corrected to remove leading zero</code>
2. Use parseInt(string, radix)
The parseInt() function takes a string as an argument and allows for specifying the radix (base) in which the string should be interpreted. For decimal numbers, use a radix of 10, as follows:
<code class="javascript">var x = parseInt("010", 10);</code>
Conclusion
To prevent leading-zero numbers from being treated as octals in JavaScript, it's recommended to remove leading zeros or use parseInt() with a radix of 10. This ensures that numbers are consistently parsed in base 10, regardless of the JavaScript mode used.
The above is the detailed content of Why Does JavaScript Interpret Leading-Zero Numbers as Octals?. For more information, please follow other related articles on the PHP Chinese website!