tags:

views:

11528

answers:

5

What is the difference in using the delete array element as opposed to the array.splice method.

Why even have the splice method if i can delete elements in the array like i can with objects?

for ex:

myArray = ['a', 'b', 'c', 'd']; delete myArray[1];

    or

myArray.splice (1,1);

what's the difference?

+5  A: 

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", "undefined", "c", "d"

myArray = ['a', 'b', 'c', 'd']; delete myArray[1];

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

Whereas this will display "a", "c", "d"

myArray = ['a', 'b', 'c', 'd']; myArray.splice (1,1);

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}
andynormancx
+14  A: 

Delete won't remove the element from the array it will only set the element as undefined.

So,

myArray = ['a', 'b', 'c', 'd'];
delete myArray[0];
[undefined, 'b', 'c', 'd'];


myArray = ['a', 'b', 'c', 'd'];
myArray.splice (0,1);
['b', 'c', 'd'];
Andy Hume
correction for line 3: [undefined, 'b', 'c', 'd'] (it's not the string 'undefined', but the special value undefined)
Jasper
@Jasper, fixed `'undefined'` => `undefined`
Motti
+2  A: 

From Core JavaScript 1.5 Reference > Operators > Special Operators > delete Operator :

When you delete an array element, the array length is not affected. For example, if you delete a[3], a[4] is still a[4] and a[3] is undefined. This holds even if you delete the last element of the array (delete a[a.length-1]).

f3lix
A: 

splice will work with numeric indices.

whereas delete can be used against other kind of indices..

example delete myArray['text1'];

Gopal
A: 

also check out Resig's array remove: http://ejohn.org/blog/javascript-array-remove/

zack