I have a deck of cards object that essentially just fills a deck array with 0-51 (52 cards) and then shuffles the cards. I have a cards.deal() method that returns a card. When I use cards.pop() I always get a different number, which is what is expected; however, when I used cards.shift() it always returns 0. I'm content with using pop but would just like to understand for learning purposes why I'm always getting a 0 when I use shift. I've changed the number of shuffles to huge numbers like 10,000 just to make sure it's shuffling enough to actually swap the first element in the array. Could it be possible that the Math.ceil method is not returning a 0, even after 10,000 random numbers generated between 0 and 51? What is going on here?
function Deck(){
var cards = [];
this.shuffle = function(){
var tempCardHolder = 0;
var randomNumber = 0;
var randomNumber2 = 0;
// fill the card array with 52 cards
for (x = 0; x <= 51; x++){
cards[x] = x;
}
// now let's shuffle them up by swapping two cards randomly 50 times
for (y = 0; y < 100; y++){
// make sure we get two random numbers that are different
do {
randomNumber = Math.ceil(Math.random() * 51);
randomNumber2 = Math.ceil(Math.random() * 51);
} while (randomNumber == randomNumber2);
tempCardHolder = cards[randomNumber];
cards[randomNumber] = cards[randomNumber2];
cards[randomNumber2] = tempCardHolder;
}
}
this.deal = function(){
return cards.shift();
}
this.getNumCardsLeft = function(){
return cards.length;
}
}