为什么 [1, 2, , 4, 5] 是一个有效的 JavaScript 数组?
Why is [1, 2, , 4, 5] a valid JavaScript array?
我最近遇到了一个错误,在 JavaScript 数组中不小心出现了太多逗号,这让我们想到了今天的问题:为什么
[1, 2, , 4, 5]
一个有效的 JavaScript 数组而不是语法错误? ECMAScript 标准中是否明确定义了允许使用 emply 元素?看起来很容易打错字。
有关更多信息,请注意 [1, 2, , 4, 5][2];
是 undefined
。
这种数组称为稀疏数组。
Is it clearly defined in the ECMAScript standard that emply elements should be allowed?
是的,是的。参见 https://tc39.github.io/ecma262/#sec-array-initializer
Array elements may be elided at the beginning, middle or end of the element list [of an ArrayLiteral]. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.
在语法中,查找非终结符 Elision。
我最近遇到了一个错误,在 JavaScript 数组中不小心出现了太多逗号,这让我们想到了今天的问题:为什么
[1, 2, , 4, 5]
一个有效的 JavaScript 数组而不是语法错误? ECMAScript 标准中是否明确定义了允许使用 emply 元素?看起来很容易打错字。
有关更多信息,请注意 [1, 2, , 4, 5][2];
是 undefined
。
这种数组称为稀疏数组。
Is it clearly defined in the ECMAScript standard that emply elements should be allowed?
是的,是的。参见 https://tc39.github.io/ecma262/#sec-array-initializer
Array elements may be elided at the beginning, middle or end of the element list [of an ArrayLiteral]. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.
在语法中,查找非终结符 Elision。