倚天杖
2022-09-23 16:57:02
我正在嘗試將循環(huán)輸出保存到一個(gè)數(shù)組中。如果我控制臺(tái).log(arr2),我得到了我想要的結(jié)果,但在多個(gè)數(shù)組中。我想把所有這些東西都放在一個(gè)數(shù)組中。當(dāng)我嘗試使用 .push 時(shí),所有數(shù)組都會(huì)產(chǎn)生相同的值。也許我可以以其他方式做到這一點(diǎn),但我不知道該怎么做。 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 }]當(dāng)我控制臺(tái).log(arr2)在for循環(huán)中時(shí),我得到了幾乎我想要的東西,想要的結(jié)果,但不是在單個(gè)數(shù)組中。 [ { 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貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超10個(gè)贊
這是因?yàn)閷?duì)象通過引用工作。這應(yīng)該有效: 替換這個(gè):
arr2 = arr1.map(function(record){
record.value1 = b.value1;
record.value3 = b.value3;
record.value4 = b.value4;
return record;
})
通過您的代碼中的這個(gè):
arr2 = arr1.map(function(record) {
const tempRecord = {...record}
tempRecord.value1 = b.value1;
tempRecord.value3 = b.value3;
tempRecord.value4 = b.value4;
return tempRecord;
})
你可以通過這樣做來完成最終結(jié)果:arr3.flat();
添加回答
舉報(bào)
0/150
提交
取消