JS forEach循环后数组所有对象值被覆盖,如何按当前索引生成目标数组
问题根因
问题是由JavaScript引用类型的特性导致的:
- 代码中
let pushValue = tempResp只是把tempResp的内存引用赋值给了pushValue,并没有创建新的独立对象 - 循环过程中修改的始终是同一个对象的
plants属性,最后数组里的所有元素都指向同一个对象,自然全是最后一次修改的结果
解决方法
每次循环时创建一个新的对象副本,再修改副本的plants属性后推入数组即可,不需要额外引入chunk也可以实现,修改后的代码如下:
loop() { let newArray = []; // 直接遍历原plants数组即可 this.resp.plants.forEach(plant => { // 用扩展运算符创建新的对象副本,避免修改原对象 let pushValue = { ...this.resp, // 把当前plant赋值给新对象的plants属性 plants: [plant] }; newArray.push(pushValue); }); console.log(newArray); // 输出结果符合预期 }
如果要保留你原来的chunk写法,只需要修改循环内的赋值逻辑即可:
loop() { let newArray = []; let tempResp = this.resp; const val = chunk(tempResp.plants, 1); val.forEach(plant => { // 每次创建新的对象副本 let pushValue = { ...tempResp, plants: plant }; newArray.push(pushValue); }); }
补充说明
如果实际业务中resp对象层级更深,浅拷贝无法满足需求,可以用structuredClone做深拷贝:
let pushValue = structuredClone(tempResp); pushValue.plants = plant; newArray.push(pushValue);
内容的提问来源于stack exchange,提问作者FE-Deve
相关产品推荐
相关产品推荐

