简体   繁体   English

array.push添加到错误的数组

[英]array.push adding to wrong array

I have created 2 arrays, answeredArr and correctArr ; 我已经创建2个阵列, answeredArrcorrectArr ; 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); 此后,每次我answeredArr.push(variable); , correctArr is updated as well. correctArr也将更新。

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. 当您执行objB = objAobjAobjB指向内存中的相同位置,换句话说,它们是同一事物,只是名称不同。

Luckily, Array has a built in method Array.prototype.slice which makes cloning it easy. 幸运的是, Array具有内置方法Array.prototype.slice ,可轻松进行克隆。

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: Javascript中的数组是通过引用而不是值来处理的,因此在执行此操作时:

answeredArr = correctArr;

you set the reference to answeredArr to be the same as the refrence to correctArr. 您将对AnswerArr的引用设置为与对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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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