我正在尝试将循环输出保存到一个数组中。如果我控制台.log(arr2),我得到了我想要的结果,但在多个数组中。我想把所有这些东西都放在一个数组中。当我尝试使用 .push 时,所有数组都会产生相同的值。也许我可以以其他方式做到这一点,但我不知道该怎么做。 let b = {}; let arr3 = []; let arr1 = [{value1: 123, value2: 34, value3: 90, value4: 23, value5: 32},{value1: 10, value2: 09, value3: 54, value4: 32, value5: 311}]; for (let a = 0; a <=4; a++){ b = {"value1": a*a, "value3": a+12, "value4": a/2}; arr2 = arr1.map(function(record){ record.value1 = b.value1; record.value3 = b.value3; record.value4 = b.value4; return record; }) // console.log(arr2); arr3.push(arr2);}console.log(arr3);这就是我用.push完成的,这不是我想要的。 [ { value1: 0, value2: 34, value3: 12, value4: 0, value5: 32 }, { value1: 0, value2: 9, value3: 12, value4: 0, value5: 311 }][ { value1: 1, value2: 34, value3: 13, value4: 0.5, value5: 32 }, { value1: 1, value2: 9, value3: 13, value4: 0.5, value5: 311 }][ { value1: 4, value2: 34, value3: 14, value4: 1, value5: 32 }, { value1: 4, value2: 9, value3: 14, value4: 1, value5: 311 }][ { value1: 9, value2: 34, value3: 15, value4: 1.5, value5: 32 }, { value1: 9, value2: 9, value3: 15, value4: 1.5, value5: 311 }][ { value1: 16, value2: 34, value3: 16, value4: 2, value5: 32 }, { value1: 16, value2: 9, value3: 16, value4: 2, value5: 311 }]当我控制台.log(arr2)在for循环中时,我得到了几乎我想要的东西,想要的结果,但不是在单个数组中。 [ { value1: 0, value2: 34, value3: 12, value4: 0, value5: 32 }, { value1: 0, value2: 9, value3: 12, value4: 0, value5: 311 }][ { value1: 1, value2: 34, value3: 13, value4: 0.5, value5: 32 }, { value1: 1, value2: 9, value3: 13, value4: 0.5, value5: 311 }][ { value1: 4, value2: 34, value3: 14, value4: 1, value5: 32 }, { value1: 4, value2: 9, value3: 14, value4: 1, value5: 311 }][ { value1: 9, value2: 34, value3: 15, value4: 1.5, value5: 32 }, { value1: 9, value2: 9, value3: 15, value4: 1.5, value5: 311 }][ { value1: 16, value2: 34, value3: 16, value4: 2, value5: 32 }, { value1: 16, value2: 9, value3: 16, value4: 2, value5: 311 }]
1 回答
慕哥6287543
TA贡献1831条经验 获得超10个赞
这是因为对象通过引用工作。这应该有效: 替换这个:
arr2 = arr1.map(function(record){
record.value1 = b.value1;
record.value3 = b.value3;
record.value4 = b.value4;
return record;
})
通过您的代码中的这个:
arr2 = arr1.map(function(record) {
const tempRecord = {...record}
tempRecord.value1 = b.value1;
tempRecord.value3 = b.value3;
tempRecord.value4 = b.value4;
return tempRecord;
})
你可以通过这样做来完成最终结果:arr3.flat();
添加回答
举报
0/150
提交
取消