1

Okay, so I am pulling my hair out with this one. I am trying to make a function that will shuffle a virtual deck of cards. I saw examples online, but they were written in some syntax I am unfamiliar with. I really couldn't understand what was going on so I tried to write my own. Anyway, the way I am going about it, I am making a duplicate array and then randomly picking cards out of the first array and putting them into the second array one by one, then deleting the randomly selected card. Here's my code. The function is stopping once the length of the original array reaches 26.

shuffleDeck: function (deck) {
        var newDeck = deck;
        for (i = 0; i<newDeck.length;i++){
            randomIndex = Math.floor(Math.random() * deck.length);
            newDeck[i] = deck[randomIndex];
            deck.splice(randomIndex,1);  
            console.log(deck.length);
        }

        return newDeck;
    }
jacobsa
  • 5,719
  • 1
  • 28
  • 60
user3291465
  • 23
  • 1
  • 1
  • 3

1 Answers1

0

Arrays are passed by reference in JavaScript so the splice is removing from the array which is why it stops

See http://orizens.com/wp/topics/javascript-arrays-passing-by-reference-or-by-value/

You can do

var newDeck = deck.slice(0);

For a copy

Chris Muench
  • 17,444
  • 70
  • 209
  • 362
  • Bam! I had no idea they were passed by reference! This fixed it right up. Thanks so much! So objects and arrays are passed by reference. Any other types whose variables behave that way?? – user3291465 Jul 12 '15 at 01:31