ep0
ep0

Reputation: 710

Delete array by index

I'm having a little trouble with the JS delete() function.

Straight from Chrome Inspector:

> x = [{name: 'hello'}, {name: 'world'}]
> [Object, Object]
> delete x[0]
> true
> $.each (x, function (i, o) {console.log(o.name);})
> TypeError: Cannot read property 'name' of undefined
> x
> [undefined × 1, Object]

Do you have any idea why this is happening? It's causing me issues with that each

Upvotes: 0

Views: 376

Answers (3)

stavarotti
stavarotti

Reputation: 582

The delete() method on the Array data structure is a little misleading. When you do the following:

var a = ['one', 'two', 'three'];
delete a[0];

delete() does something similar to assigning the array element to undefined. Note that after using delete(), the array is not shifted and the length remains the same:

a.length -> 3
a[0] -> undefined

So in essence, delete() creates a sparse array and does not alter the length property nor remove the element. To completely remove the element, you want to do the following:

a.splice(0,1)

This will both remove the element and alter the array's length property. So now:

a.length -> 2

See the the splice method for details on method arguments.

Upvotes: 0

Steven Schobert
Steven Schobert

Reputation: 4269

To properly remove objects from the array, you should use the splice method.

x = [{name: 'hello'}, {name: 'world'}];
x.splice(0,1);

Upvotes: 1

Pointy
Pointy

Reputation: 413702

Deleting x[0] is not the same as slicing that entry out of the array. Element 1 is still at x[1] in other words, so x[0] is undefined.

Upvotes: 1

Related Questions