首页 > 解决方案 > 在数组中添加属性。添加所有数组中的最后一个值

问题描述

“我在 forEach 循环中在数组上添加一个属性。但是当我执行 console.log() 时,每个数组上的附加值始终是 foreach 循环的最后一个值。”

交货数据有位置,我想将位置传递给pickupDetails。

   deliveries: [{  //data of deliveries that I want to pass in pickupDetails
     0: {Location: Korea},
     1: {Location: Japan}
   }]

   let pickupDetails = this.state.pickupDetails;

   //pickupDetails is only one object then It will become two since the deliveries has 2 objects
   pickupDetails = {
      name: "June"
   }


   this.state.deliveries.forEach((delivery, index) => {
       pickupDetails.location = delivery.location;
       console.log(pickupDetails)
   })

   the result of the console:
   pickupDetails = {
       name: "June"
       location: "Japan" //this should be Korea since the first loop data is korea
   }
   pickupDetails = {
       name: "June"
       index: "Japan"
   }

标签: reactjsforeach

解决方案


我认为该代码中缺少某些内容可能是因为它的虚拟数据。好吧,从我的角度来看,您对 javascript 参考感到困惑。

deliveries: [{  //data of deliveries that I want to pass in pickupDetails
     0: {Location: Korea},
     1: {Location: Japan}
   }]

   let pickupDetails = this.state.pickupDetails;
   this.state.deliveries.forEach((delivery, index) => {
       let newPickupDetails = JSON.parse(JSON.stringify(pickupDetails));
       newPickupDetails.location = delivery.location;
       console.log(newPickupDetails);
   })

   the result of the console:
   pickupDetails = {
       name: "Juan"
       location: "Japan" //this should be Korea since the first loop data is korea
   }
   pickupDetails = {
       name: "June"
       index: "Japan"
   }

JSON.parse 和 JSON.stringify 我们用于创建新对象而不是使用引用。控制台日志受到影响,因为它通过引用链接,所以如果你将它设为新对象,它就会这样做。

检查变量 newPickupDetails


推荐阅读