Hunter
Hunter

Reputation: 25

JavaScript splice problem

A have an array of Objects and I'd like to remove the first element from it and read some of its properties. But I can't. Here is the code:

$.test = function(){
 var array = [
  {a: "a1", b: "b1"},
  {a: "a2", b: "b2"},
  {a: "a3", b: "b3"}
 ];
 alert("0. element's 'a': " + array[0].a); 
 alert("length: " + array.length);

 var element = array.splice(0, 1);
 alert("length: " + array.length);
 alert("removed element's 'a': " + element.a);   
}

I get:

3
a1
2
undefined

Why do I always get "undefined"? The splice method is supposed to remove the defined element(s) and return it / them.

Upvotes: 1

Views: 3114

Answers (2)

The Scrum Meister
The Scrum Meister

Reputation: 30111

splice returns a array of the removed elements.

this should work

alert("removed element's 'a': " + element[0].a);

Upvotes: 2

Hemlock
Hemlock

Reputation: 6210

You can use shift to accomplish this - it removes and returns the first element in an array.

Your problem is that splice returns an array so your code would have to be:

alert("removed element's 'a': " + element[0].a);

Upvotes: 6

Related Questions