只需看一下代码,您就会明白我的意思:

​var aBackup = [3, 4]; // backup array
​​var a = aBackup; // array to work with is set to backup array
a[0]--; // working with array..
a = aBackup; // array o work with will be rested
console.log(a);  // returns [2, 4] but should return [3, 4]
console.log(aBackup);​ // returns [2, 4] too​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​  but should return [3, 4] too

最佳答案

您需要制作数组的真实副本,而不仅仅是使用引用:

var aBackup = [3, 4]; // backup array
var a = aBackup.slice(0); // "clones" the current state of aBackup into a
a[0]--; // working with array..
a = aBackup.slice(0); // "clones" the current state of aBackup into a
console.log(a);  // returns [3, 4]
console.log(aBackup); // returns [3, 4]


有关slice方法的文档,请参见MDN

关于javascript - JavaScript创建使用备份阵列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9785235/

10-13 23:06