-1

I have created 2 arrays, answeredArr andcorrectArr; to hold info for a game. The first time the game is completed I copy the correct answers array to the answers array:

answeredArr = correctArr;

After this point, every time I answeredArr.push(variable);, correctArr is updated as well.

There is a lot of code, so I'm reluctant to post it all.

RasMason
  • 1,968
  • 4
  • 32
  • 54

2 Answers2

4

An Array is an Object. When you do objB = objA, objA and objB point to the same place in memory, in other words they are the same thing under different names.

Luckily, Array has a built in method Array.prototype.slice which makes cloning it easy.

var a1 = [], a2;
a2 = a1;         // a1 === a2
a2 = a1.slice(); // a1 !== a2, but identical.
Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

Arrays in Javascript are handled by reference, not value, so when you do this:

answeredArr = correctArr;

you set the reference to answeredArr to be the same as the refrence to correctArr. Thereafter, any operation on one will also affect the other, since they're pointing to the same array.

You need to clone the array, rather than copy the reference. An easy way to do this is:

var answeredArr = correctArr.slice(0);