JavaScript splice problem - Stack Overflow

A have an array of Objects and I'd like to remove the first element from it and read some of its p

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 badges
Add a ment  | 

2 Answers 2

Reset to default 6

You 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

相关推荐

  • JavaScript splice problem - Stack Overflow

    A have an array of Objects and I'd like to remove the first element from it and read some of its p

    1天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信