【问题标题】:Issue pushing to array from nested loop从嵌套循环推送到数组的问题
【发布时间】:2020-02-26 23:38:18
【问题描述】:

当我运行此程序时,除了数组推送外,一切正常。 console.log(notificationdata);显示通知数据正确更新了它的值,但然后查看 console.log(notifications) 我有 7 个相同的值,其值与来自通知数据的最后一个匹配。不知何故,推送到阵列没有正确发生,我似乎无法弄清楚。有什么想法吗?

var notifications = [];
reminder.days.value = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
reminder.times = [00:00]

      var notificationdata = {
        title: "Nu är det dags att ta en dos",
        text: "Ta " + medication + " mot " + affliction + " nu.",
        smallIcon: "../images/DosAvi_badge.png",
        icon: "../images/DosAvi_icon.png",
        every: "week",
        foreground: true
      }
      notificationdata.id = reminder.id;
      for(const day of reminder.days.value){
        for(const time of reminder.times){
          notificationdata.firstAt = getNextDayOfTheWeek(day, new Date(`Mon Jan 01 2020 ${time}`));
          //notificationdata.firstAt = new Date(`Wen Feb 26 2020 21:55`);
          console.log(notificationdata);
          notifications.push(notificationdata);
        }
      }
      console.log(notifications)

      cordova.plugins.notification.local.schedule(notifications);
    }

【问题讨论】:

  • 您可以尝试不使用 const in for,这样 timeday 可能会发生变化。将其更改为 let 或只是 var.

标签: javascript arrays for-loop nested-loops


【解决方案1】:

notificationdata 是一个对象,在你的循环中你只是改变了这个对象的一个​​属性。对数组的推送将对象的引用添加到数组。因此,您最终会得到一个包含 7 个对同一对象的引用的数组。要解决此问题,您必须先复制对象:

      for(const day of reminder.days.value){
        for(const time of reminder.times){
          const copyNotificationdata = {
              ...notificationdata,
              firstAt: getNextDayOfTheWeek(day, new Date(`Mon Jan 01 2020 ${time}`))
          }
          notifications.push(copyNotificationdata);
        }
      }

【讨论】:

    【解决方案2】:

    因为您不创建新对象而只是重复使用相同的对象。

    Javascript 对象变量仅保存对对象的引用。这意味着您始终更新内存中的相同数据,并且您的数组包含对同一对象的 7 个引用。

    您必须创建一个新对象并将其插入到您的数组中:

    for(const day of reminder.days.value){
        for(const time of reminder.times){
            const newNotificationdata = { ...notificationData };
            newNotificationdata.firstAt = getNextDayOfTheWeek(day, new Date(`Mon Jan 01 2020 ${time}`));
            notifications.push(newNotificationdata);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-22
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 2021-05-17
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多