(We do not claim that garbage collection is infallible in all implementations. If you are comfortable with the concept of ghosts in your arrays, the slicing and splicing operations are highly regular.Ī note on exorcism: If you delete an array, you delete the ghosts. If you ask JavaScript about Array.length you will see the evidence that ghosts are there. If you ask JavaScript about the ghosts, it will disavow their existence. Ghost elements fill in the discontinuous elements while the operations are performed. Slicing and splicing sparse arrays is defined as if the arrays were contiguous.
(The final array is seven long: original ten minus five deleted plus two inserted.) Again, ghosts count. Then an additional step inserts the new values. For a clear mental picture, after the deletion you can think of the array as also unaffected by the insertion. The value returned by the splice operation is the same as it was without the insertion. You may want to make a copy of our Array Quick Reference page.) (Remember that when the "end" argument is specified, the values are returned up to, but not including, "end" The results of the slices appear to be slices from a contiguous array containing elements zero through nine. Because we assign to array, it's length is ten. In the following example, we create a sparse array. It also has no ability to insert new values. It extracts values from an array, but does not change the array-it just returns the extracted values. (This is true even if you delete the final element.) Importantly, the non-existing elements have a certain ghostly existence. Deleting elements does not change the array's length. The above array, after the deletion, has two elements named "0" and "2". If old Uncle Fred passed away but his ghost still haunts the attic, would you say he's "gone"? Var array1 = ĭid we say "gone"? Well, almost. This may be created by assignments to non-contigous elements or by deletion of elements: We will leave implementation details to the implementors from now on and only consider the appearance the array has for the programmer.įor a programmer, a sparse array is one which may have non-contiguous subscripts. A non-sparse implementation could create a contiguous array of sixteen elements, leaving five empty spaces.
Internally, as in JavaScript, a non-sparse array may be implemented as a sparse array so that assigning another element, say array (when elements zero through nine are defined and length is ten) is not a problem. This does not appear "sparse" to the programmer.
Assume that an array of ten elements, holding ten values, is created.
The term "sparse array" refers both to an implementation technique and to the toolset available to the programmer.