ga-wdi-exercises / project1

[project] GA- Project 1
3 stars 75 forks source link

Issue with pushing objects into array #158

Closed tomiteo closed 9 years ago

tomiteo commented 9 years ago

I'm working on the JS underpinning War, and I'm encountering unexpected behavior:

var card = {
  value : null,
  suit : null,
};

var createCard = function(value){
  var newCard=card;
  newCard.value=value;
  return newCard;
};

var createDeck = function(){
  var newDeck=[];
  console.log(newDeck);
  for (var i = 2; i <= 14; i++) {
    var newCard = createCard(i);
    console.log(newCard);
    newDeck.push(newCard);
    console.log(newDeck);
  }
};

createDeck();

I expected createDeck() to create an array of objects, each with its own value property of 2-14, but instead the console displayed an array of objects, all with value 14

jsm13 commented 9 years ago

Short answer is that there is only one card. The original card declared. Every assignment has passed a reference to that same first card. You'll want to fix this by creating the card within createCard

RobertAKARobin commented 9 years ago

Gahh, John beat me! I'm answering anyway.

Ooh, interesting! This is a little weird. Whenever you say var newCard = card, Javascript doesn't create a copy of card, it just uses the same old card. If you want to create a whole new card, you'll need to do something like:

var createCard = function(value){
  var newCard = {
    value: null,
    suit; null
  };
  newCard.value=value;
  return newCard;
};
tomiteo commented 9 years ago

wow! it's working now! thanks guys!

tomiteo commented 9 years ago

so my understanding is that each index of the array was at first just referencing the same one card over and over again, but now with var newCard = { value: null, suit: null }; it's creating a new object each time

RobertAKARobin commented 9 years ago

Yup!

jsm13 commented 9 years ago

Bit on mutability and referencing objects in eloquent js