JavaScript splice problem
A have 开发者_StackOverflowan 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.
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);
splice
returns a array of the removed elements.
this should work
alert("removed element's 'a': " + element[0].a);
精彩评论