for循环赋值,数组全部变成最后一条

const testArr = [
   { aa: '1', bb: '11', cc: '111' },
   { aa: '2', bb: '22', cc: '333’ }
 ]
 const arr = []
 const test = { dd: '444', fff: '555', ggg: '0' }
 testArr.forEach(item => {
   test.ggg = item.cc
   arr.push(test)
 })
 console.log('arr', arr)

在这里插入图片描述
为什么不是这样[{dd: “444”, fff: “555”, ggg: “111”},{dd: “444”, fff: “555”, ggg: “333”}]?

因为每次 push() 的都是同一个对象的引用地址,你应该每次循环都创建一个新的对象,才能让每次 push() 的对象引用地址不一样。

const testArr = [
  { aa: '1', bb: '11', cc: '111' },
   { aa: '2', bb: '22', cc: '222' }
 ]
 const arr = []

 testArr.forEach(item => {
   const test = { dd: '444', fff: '555', ggg: '0' }
   test.ggg = item.cc
   arr.push(test)
 })
 console.log('arr', arr)

需求: 将cs1数组中的list数组替换成cs2,但是相对应的cabinId不能修改,(即对应的cabin修改为cs2中的值)
结果如图:
在这里插入图片描述

const cs1 = [
   {
     list: [
       {
         cabin: 'H',
         cabinId: '11'
       },
       {
         cabin: 'H',
         cabinId: '12'
       }
     ]
   },
   {
     list: [
       {
         cabin: 'H',
         cabinId: '21'
       },
       {
         cabin: 'H',
         cabinId: '22'
       }
     ]
   }
 ]
 const cs2 = [
   {
     cabin: 'H1',
     cabinId: '11'
   },
   {
     cabin: 'H2',
     cabinId: '12'
   }
 ]

方法一:结果符合要求

for (const item of cs1) {
 item.list.forEach((i, index1) => {
    cs2.forEach((j, index2) => {
      if (index1 === index2) {
        i.cabin = j.cabin
      }
    })
  })
}
console.log('result : ', cs1)

方法二:倘若只需要修改一个cabin,这样很方便,倘若需要替换的list中每个条目的obj对应的特别多,那这样赋值就显得非常臃肿,故能不能直接先将没给对象的id存储下来,然后将cs2中的obj赋值给cs1[i].list[j],方法如下

for (const item of cs1) {
   for (let i = 0; i < item.list.length; i++) {
     const cabinId = item.list[i].cabinId
     for (let j = 0; j < cs2.length; j++) {
       if (i === j) {
         console.log('i = ', i, 'j = ', j, 'cabinId = ', cabinId)
         // i =  0 j =  0 cabinId =  11
         // i =  1 j =  1 cabinId =  12
         // i =  0 j =  0 cabinId =  11
         // i =  1 j =  1 cabinId =  12
         item.list[i] = cs2[j]
         item.list[i].cabinId = cabinId
       }
     }
   }
 }
 console.log('result : ', cs1)

在这里插入图片描述

结果并不是自己期望的结果

处理方法:在for循环中新建一个对象

for (let item of cs1) {
  const itemCopy = JSON.parse(JSON.stringify(item))
  for (let i = 0; i < itemCopy.list.length; i++) {
    const cabinId = itemCopy.list[i].cabinId
    for (let j = 0; j < cs2.length; j++) {
      if (i === j) {
        itemCopy.list[i] = cs2[j]
        itemCopy.list[i].cabinId = cabinId
      }
    }
  }
  item = itemCopy
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值