繁体   English   中英

为什么在循环中总是为 object 中的元素分配相同的值 | VueJS

[英]Why an element in an object is always assigned the same value in a loop | vueJS

我想我很难理解 javascript 或更准确地说是 vuejs 在这种情况下如何工作......

给出以下代码:

....
data() {
   campaigns: [{id: 1, name: 'Campaign 1'}, {id: 2, name: 'Campaign 1'}]
   campaignsWithEventSettings: [0, 1] //these are the indexes for campaigns
},

methods: {
   saveOrUpdate() {
     let campaigns = [];

     this.campaignsWithEventSettings.map(x => {
          let campaign = this.campaignsSettings[x];
          campaign.event_settings = true;
          console.log(this.campaigns[x].id) //screenshot with the result is attached below 
          campaign.id = this.campaigns[x].id;
          campaigns.push(campaign);
     });
            
     //that gives the same result 
     /*for (let i = 0; i < this.campaignsWithEventSettings.length; i++) {
          let idx = this.campaignsWithEventSettings[i];
          let campaign = this.campaignsSettings[idx];
          campaign.event_settings = true;
          campaign.id = this.campaigns[idx].id;
          campaigns.push(campaign);
     }*/

     let settings = [];
     settings.push({eventId: this.eventId});
     settings.push({campaigns: campaigns});

     axios.post('/events/campaigns', settings).then(resp => {
          console.log(resp)
     })
  },
}

....

问题是最后,所有活动都具有相同的 id,尽管在运行 console.log 时日志 id 不同/正确。 所以换句话说,在每个循环中,数组中的所有活动都会收到一个新的 id(最后一个)。

console.log screenshot_console

请求screenshot_request_data

所以我会引用问题所在,并在链接中放置更详细的信息。

当您使用在 scope 之外声明的变量时,将使用该变量,它将使用该变量在运行时的值。 在设置关闭时,它不会获得值的副本。 如果您将闭包视为指针而不是值,那么这可能会有所帮助。

来源: https://dzone.com/articles/why-does-javascript-loop-only-use-last-value

这意味着您的变量let campaign = this.campaignsSettings[x]; is using 始终是 X 的最后一个。因为您的 X 是 scope 中的变量,所以当您尝试 output 循环的索引时,这很常见。

一个快速的解决方案是包装一个函数!

for(let x of this.campaignsWithEventSettings){
  (function (newX){
    let campaign = this.campaignsSettings[newX];
    campaign.event_settings = true;
    campaign.id = this.campaigns[newX].id;
    campaigns.push(campaign);
  })(x);
}

或类似的东西

for(let x of this.campaignsWithEventSettings){
  try{throw x}
  catch(newX){
    let campaign = this.campaignsSettings[newX];
    campaign.event_settings = true;
    console.log(this.campaigns[newX].id)
    campaign.id = this.campaigns[newX].id;
    campaigns.push(campaign);
  }
}

我会做以下事情:

 let campaigns = this.campaignsWithEventSettings.map(x => {
      let campaign = this.campaignsSettings[x];
      campaign.event_settings = true;
      campaign.id = this.campaigns[x].id;
      return campaign
 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM