Ender Ady
Ender Ady

Reputation: 59

variable copies wrong content js

This is all the js code, when i console log the raw variable it returns the shuffled deck, I do not understand that, i am new to js and i've tried this. but i don't really know how it works, also, what's the difference between var and let if you guys dont mind me asking? thank you.

function drawDeck(){
  var deck = []
  var value = [2,3,4,5,6,7,8,9,10,10,10,10,11]
  for(var i=0;i<4;i++){
    for (var j=0;j<13;j++){
      deck.push(value[j])
    }
  }
  return deck
}

function shuffleDeck(deck){
  var currentPos = deck.length, tempPos , randPos
  while (currentPos != 0){
    randPos = Math.floor(Math.random() * currentPos)
    currentPos -= 1
    tempPos = deck[currentPos]
    deck[currentPos] = deck[randPos]
    deck[randPos] = tempPos
  }
  return deck
}

function drawCard(deck){
  var card = deck.shift()
  return card
}
var raw = drawDeck()
var deck = shuffleDeck(raw)
var card = drawCard(deck)
console.log(raw)

Upvotes: 0

Views: 41

Answers (1)

Honkalonkalooooohhh
Honkalonkalooooohhh

Reputation: 141

The shuffle function operates on the input element itself. Since you input raw to the shuffle function it self will be modified and thus you get the shuffled deck when logging it. It doesn't matter if it gets returned or not.

If you wanna preserve the original array, clone the array to a new variable inside the shuffle function and do the shuffling on the clone and return that.

var raw = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
var shuffled;

function shuffleDeck(deck) {
  var currentPos = deck.length,
    tempPos, randPos
    var tempDeck = Array.from(deck);
  while (currentPos != 0) {
    randPos = Math.floor(Math.random() * currentPos)
    currentPos -= 1
    tempPos = tempDeck[currentPos]
    tempDeck[currentPos] = tempDeck[randPos]
    tempDeck[randPos] = tempPos
  }
  return tempDeck
}
shuffled = shuffleDeck(raw);
alert('original: ' + raw);
alert('shuffled: ' + shuffled);

Upvotes: 1

Related Questions