Javascript 0 在数字的开头
我只是想了解以 0-s 开头的 js 逻辑.例如
I just want to understand js logic with 0-s in beginning of number. For example
var x = 09.3
// here x == 9.3
// other example
09.3 == 9.3
// returns true
// but check this one
var x = 02.5
// Uncaught SyntaxError: Unexpected number
// or this one
02.5 == 2.5
// same error here
谁能解释一下,它是如何工作的,为什么在第一个例子中它工作,并忽略前导零,但在第二个例子中它给了我一个 SyntaxError
Can anyone explain, how it works, why in first example it works, and ignores leading zeros, but in second example it gives me a SyntaxError
谢谢
推荐答案
数字文字前导 0
表示意图使用八进制整数,除非 第二位是8
或9
.在这种情况下,前导 0
将被忽略.
Leading 0
on a numerical literal indicates that an octal integer is the intention, unless the second digit is 8
or 9
. In that case, the leading 0
is ignored.
因为八进制数字字面量必须是整数,所以 02.5
是错误的.
Because octal numeric literals must be integers, 02.5
is erroneous.
此行为在 2014 年被记录为 Firefox 中的一个错误,但由于世界上有如此多的 JavaScript 代码,而且其中很多(可能是无意的)依赖于 09.3
而不是语法错误,该错误被标记为WONTFIX".
This behavior was logged as a bug in Firefox in 2014, but because there's so much JavaScript code in the world and so much of it (probably inadvertently) relies on 09.3
not being a syntax error, the bug was marked "WONTFIX".
正如下面评论中指出的,在严格"模式下,八进制常量是完全不允许的.
As pointed out in a comment below, in "strict" mode octal constants are disallowed entirely.
相关文章