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.
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.
Share asked Jan 10, 2011 at 18:26 HunterHunter 252 silver badges5 bronze badges2 Answers
Reset to default 6You can use shift
to acplish 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);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744908203a4600386.html
评论列表(0条)