Sparse Arrays
A sparse array is one in which the elements
do not have contiguous indexes starting at 0. Normally, the length property of an array specifies the
number of elements in the array. If the array is sparse, the value of
the length property is greater than
the number of elements. Sparse arrays can be created with the Array() constructor or simply by assigning
to an array index larger than the current array length.
a=newArray(5);// No elements, but a.length is 5.a=[];// Create an array with no elements and length = 0.a[1000]=0;// Assignment adds one element but sets length to 1001.
We’ll see later that you can also make an array sparse with the
delete operator.
Arrays that are sufficiently sparse are typically implemented in a slower, more memory-efficient way than dense arrays are, and looking up elements in such an array will take about as much time as regular object property lookup.
Note that when you omit a value in an array literal (using
repeated commas as in [1,,3]) the resulting array
is sparse and the omitted elements simply do not exist:
vara1=[,];// This array has no elements and length 1vara2=[undefined];// This array has one undefined element0ina1// => false: a1 has no element with index 00ina2// => true: a2 has the undefined value at index 0
Some older implementations (such as Firefox 3) incorrectly
insert the undefined values in array literals with omitted values. In
these implementations [1,,3] is the same as
[1,undefined,3].
Understanding ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access