Array w / all elements (except the first) undefined returns the wrong length

var arr = ["string", , ]
console.log(arr.length)

Why is the length of arr 2, not 3?

+4
source share
1 answer

This is a feature of array literals introduced in ES3.

You can put leading or triple commas as "empty" elements

therefore it [,,,,1,2,3,,]will give an array of length 7 with the first 4, and the last will be empty.

If you put this expression in the console in Firefox 34.0.5, it will say

Array [ <4 empty slots>, 1, 2, 3, <1 empty slot> ]

Sources:

Are commas in arrays and objects part of the specification?

http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf

section 11.1.4

+1
source

Source: https://habr.com/ru/post/1569366/


All Articles