简体   繁体   中英

array.push adding to wrong array

I have created 2 arrays, answeredArr and correctArr ; 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.

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM