所以我正在尝试将数组复制到另一个数组,以便我可以在不更改原始数据的情况下对其进行更改。通常我会使用Array.prototype.slice(),但我使用的是多维数组,它似乎不起作用。 例如:
let arrayOne = ["zebra", "elephant", "lion"];
let arrayTwo = arrayOne.slice();
arrayTwo[1] = "whale";
console.log(arrayOne);
应该输出[“斑马”,“大象”,“狮子”],就好像原始阵列保持不变一样。同时:
let arrayOne = [];
for (let a = 0; a < 4; a += 1) {
arrayOne.push([]);
for (let b = 0; b < 4; b += 1) {
arrayOne[a].push({itemOne: "success"});
}
}
let arrayTwo = [];
for (let c = 0; c < 4; c += 1) {
arrayTwo.push([]);
for (let d = 0; d < 4; d += 1) {
arrayTwo[c] = arrayOne[c].slice();
}
}
arrayTwo[3][1].itemOne = "failure";
console.log("It should be a " + arrayOne[0][0].itemOne);
console.log("and it has been a " + arrayOne[3][1].itemOne);
我正试图让它输出“并且它已经取得了成功”,但它却是“失败”。关于为什么的任何想法?