views:

562

answers:

3

Hi all, i have to delete some elements of my array, but without rearrange array.

If i use "delete" to delete my elements, the "holes" take up memory?

var array=["A","B","C"];
delete array[1];  // array -> ["A", undefined, "C"]

I think the deleted element is really deleted so it isn't take up memory space, isn't true?

Thanks.

+3  A: 

You can use array.splice(1, 1); It will remove one entry at index 1. The first parameter is the index, the second one is the count.

Kaivosukeltaja
without REARRANGE it, so splice is not that i look for.
blow
+3  A: 

Entirely implementation dependent. Internally all JS representations will eventually convert to a sparse representation, but the sparese representation tends to use more memory per element and be slower to access than the non-sparse array.

For this reason removing onevalue from a dense array is unlikely to releas any memory, but after a sufficient set of elements are removed the implementation will likely convert to a sparse representation to save memory overall.

Note: the object or value at the index you delete won't be deleted immediately -- delete simply removes the property slot from the object -- the object/value will only be removed during a GC pass, and only if there are no other references.

olliej
+1  A: 

try

array.splice(index, 1);

See Mastering JavaScript Arrays.

JoshNaro
without REARRANGE it, so splice is not that i look for.
blow
The array is not rearranged with splice, the index is removed entirely.Do you mean, you do not want to remove the index from the array? If so, just set the value at that index to null.
JoshNaro