admin管理员组文章数量:1403217
I have an array of objects (say, a deck of cards):
var deck = [];
deck.push(new Card(suit, rank));
The following seems to work:
var card = deck.pop();
var card = deck.shift();
(pulling from the "top" or "bottom" of the deck respectively)
But if I want a card from the middle (say, if this was a hand of cards)
var card = deck.splice(2,1);
The object doesn't seem to get properly assigned to the variable (everything is undefined). Everything I look up says that splice should return the object that I'm removing - what am I missing?
I have an array of objects (say, a deck of cards):
var deck = [];
deck.push(new Card(suit, rank));
The following seems to work:
var card = deck.pop();
var card = deck.shift();
(pulling from the "top" or "bottom" of the deck respectively)
But if I want a card from the middle (say, if this was a hand of cards)
var card = deck.splice(2,1);
The object doesn't seem to get properly assigned to the variable (everything is undefined). Everything I look up says that splice should return the object that I'm removing - what am I missing?
Share Improve this question asked Jun 7, 2012 at 16:38 Allen GouldAllen Gould 1417 bronze badges4 Answers
Reset to default 8Try
var card = deck.splice(2,1)[0];
Since splice returns an array of the removed elements...
splice returns an array of possible removed elements, so if you remove only one element you still have an array. So:
var card = deck.splice(2, 1)[0];
splice should return an array containing the element you removed. The actual element can be obtained like:
var card = deck.splice(2,1)[0];
Just the same error as here (even a quite similiar environment :-): .splice()
returns an Array of the removed elements, not a single element. So you will need to get the first element of that array:
var card = deck.splice(2,1)[0];
本文标签: Why doesn39t splicing an object from an array in Javascript return the arrayStack Overflow
版权声明:本文标题:Why doesn't splicing an object from an array in Javascript return the array? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744394205a2604133.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论