我试图复制一个数组数组,然后修改每个子数组的相同元素。
以下代码用于复制数组的初始数组:
{
"data": [
{
"district": "sikkim district",
"food saftey": 2,
"food ": 2,
"air pollution": 0
},
{
"district": "Bhojpur",
"food saftey": 1,
"food ": 1,
"air pollution": 1
},
],
}
然后使用以下代码修改每个数组的第二个元素:
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]]
如果手动创建了复制的阵列,则forEach会正确更新:
[[1, 13, 3], [4, 14, 6], [7, 15, 9], [1, 13, 3], [4, 14, 6], [7, 15, 9]]
因此,我怀疑这与push方法有关,该方法创建对初始数组的两个实例的引用,从而将最终值集(13、14和15)应用于这两个实例。
作为push方法的替代方法,我尝试了map方法(例如,符合Duplicate an array an arbitrary number of times (javascript)),但产生了相同的结果。
对于正在发生的事情或如何使其正常运行的任何见解或建议,将不胜感激。
答案 0 :(得分:2)
您需要复制内部数组的副本,因为您需要丢失相同的对象引用。
要进行推送,您可以展开数组并稍后忽略展平。
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);
答案 1 :(得分:0)
代替concat使用reduce方法将保留相同的引用。
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 = replicated_arrays.reduce(function(a, b){
return a.concat(b);
}, []);
replicated_arrays.forEach((_ae,i) => {
_ae[1] = 10 + i;
})
console.log(replicated_arrays);
output: [[1, 10, 3], [4, 11, 6], [7, 12, 9], [1, 13, 3], [4, 14, 6], [7, 15, 9]]