首页 > 解决方案 > 复制数组数组并修改每个子数组的相同元素

问题描述

我正在尝试复制一个数组数组,然后修改每个子数组的相同元素。

以下代码用于复制数组的初始数组:

const array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const n = 2;  // replicate twice
let replicated_arrays = [];
for (let i = 0; i < n; i++) {    
    replicated_arrays.push(array);
}
replicated_arrays = [].concat.apply([], replicated_arrays);  // flatten to make one array of arrays 

然后使用以下代码修改每个数组的第二个元素:

const init = 10;
replicated_arrays.forEach(function(element, index, entireArray) {
    entireArray[index][1] = init + index;
});

所需的输出是:

[[1, 10, 3], [4, 11, 6], [7, 12, 9], [1, 13, 3], [4, 14, 6], [7, 15, 9]]

但是,上面的代码会产生以下结果:

[[1, 13, 3], [4, 14, 6], [7, 15, 9], [1, 13, 3], [4, 14, 6], [7, 15, 9]]

如果手动创建复制的数组,则 forEach 会正确更新:

let replicated_arrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9]];

因此,我怀疑它与创建对初始数组的两个实例的引用的 push 方法有关,以便将最终的一组值(13、14 和 15)应用于两个实例。

作为 push 方法的替代方法,我尝试了 map 方法(例如,按照Duplicate an array an absolute number of times (javascript)),但它产生了相同的结果。

任何有关正在发生的事情或如何使其正常工作的见解或建议将不胜感激。

标签: javascript

解决方案


您需要复制内部数组,因为您需要丢失相同的对象引用。

对于推送,您可以展开数组并稍后省略展平。

const array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const n = 2;  // replicate twice
let replicated_arrays = [];
for (let i = 0; i < n; i++) {    
    replicated_arrays.push(...array.map(a => a.slice())); // spread array
}
// no need for this! replicated_arrays = [].concat.apply([], replicated_arrays);

const init = 10;
replicated_arrays.forEach(function(element, index) {
    element[1] = init + index; // access element directly without taking the outer array
});

console.log(replicated_arrays);


推荐阅读