简体   繁体   中英

when the a comma in the Array elements will not contributes to the length of the Array

In the ECMAScript 2016 .

Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (ie, 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.

but

var a = [b=1,,] console.log(a.length) //2 comma is preceded by AssignmentExpression (b=1),and the missing array element contributes the length.i want know why?
ECMAScript says not contribut the length. I want know how the comma can not contributes the length ,except in the end of the array

A comma follows a counted element, it does not mark the start of one. A comma that is the last thing in an array is meaningless, as the preceding element was already accounted for.

You left out the last sentence of the explanation, which seems to answer your question:

If an element is elided at the end of an array , that element does not contribute to the length of the Array.

It also says that empty elements at the beginning or middle of an array do contribute to array length (because they follow counted elements, even if they're empty).

If you only had this: [,] you would have a length of 1, due to the empty undefined element at the beginning of the array before the comma.

Your example : var a = [b=1,,] only has 2 elements instead of 3, because there is nothing after the 2nd comma. The empty element after the 1st comma DOES contribute, because it is not at the end and is followed by the 2nd comma indicating that there's an index there that just has nothing in it. It's like writing [b=1, undefined] . The 2nd comma is effectively a typo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM