问题描述
我只想在数字的开头用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.
这篇关于数字开头的Javascript 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!