What is the difference between using the delete
operator on the array element as opposed to using the Array.splice
method?
For example:
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
// or
myArray.splice (1, 1);
Why even have the splice method if I can delete array elements like I can with objects?
Because delete only removes the object from the element in the array, the length of the array won't change. Splice removes the object and shortens the array.
The following code will display "a", "b", "undefined", "d"
Whereas this will display "a", "b", "d"
From Core JavaScript 1.5 Reference > Operators > Special Operators > delete Operator :
delete
will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:Note that it is not in fact set to the value
undefined
, rather the property is removed from the array, making it appear undefined. The Chrome dev tools make this distinction clear by printingempty
when logging the array.myArray.splice(start, deleteCount)
actually removes the element, reindexes the array, and changes its length.// result : myArray = ['b', 'c', 'd'];
splice
will work with numeric indices.whereas
delete
can be used against other kind of indices..example:
As stated many times above, using
splice()
seems like a perfect fit. Documentation at Mozilla: