Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

4 Answers

up vote 2 down vote accepted

Try

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

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

share|improve this answer
I could have sworn I'd tried that, but it's working. – Allen Gould Jun 8 '12 at 14:02

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];
share|improve this answer

splice should return an array containing the element you removed. The actual element can be obtained like:

var card = deck.splice(2,1)[0];
share|improve this answer

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];
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.