0

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

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

0

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.

3 Comments

I'll look into splice. I preferred delete() because I'm deleting items in an each().
What is the intent behind deleting elements while iterating over the array?
I have a list of elements in Limbo (initially empty, and then add to it). The elements have a quantity field Now I update that list, by adding more elements. For every existent element in Limbo, I update the quantity, and for elements that don't exist, I add them with quantity = 1. I iterate the elements I want to add, and if I find it in Limbo, I increase the quantity and delete the item. When iterating is done, all I have is elements that need to be added, so I once iterate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.