ga-wdi-exercises / project1

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

deleting key-pair from copy of object #164

Closed ghost closed 9 years ago

ghost commented 9 years ago

I tried...

cardQuestion = Object.keys(cardDeck)[rand];
var tempArray = cardDeck;
  delete tempArray[cardQuestion];

where cardQuestion is a variable defined as a key in cardDeck.

expecting to delete a key from tempArray object but leaving it in the global object however that line of seems to remove the key pair from both the objects?

mattscilipoti commented 9 years ago

When you assign cardDeck to tempArray, you are making a reference to the Array. Any changes to either are seen by both. You would have to clone cardDeck, so that any changes you make to the clone do not affect the original.

RobertAKARobin commented 9 years ago

Yep! This is a weird thing about Javascript (and most programming languages). It's not making a copy of the array; it's making a reference to the object that already exists.

The easiest way to clone an array is with var arrayCopy = myArray.slice().

ghost commented 9 years ago

Thank you both! I think I'm headed in the right direction now

RobertAKARobin commented 9 years ago

It may be a good idea to avoid delete, since this can cause some wacky things with arrays (particularly when you try to do stuff with array.length). A better bet may be .splice() (not to be confused with .splice()... I know, I know).