Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't splicing an object from an array in Javascript return the array?

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?

like image 837
Allen Gould Avatar asked Aug 20 '26 19:08

Allen Gould


1 Answers

Try

var card = deck.splice(2,1)[0];

Since splice returns an array of the removed elements...

like image 71
Esailija Avatar answered Aug 22 '26 10:08

Esailija



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!