从嵌套循环推送到数组的问题

Issue pushing to array from nested loop

当我 运行 这一切都正常工作,除了数组推送。 console.log(通知数据);显示通知数据正确更新了它的值,然后查看 console.log(notifications) 我有 7 个相同的值与 notificationdata 中的最后一个匹配。以某种方式推送到阵列没有正确发生,我似乎无法弄清楚。有什么想法吗?

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);
    }

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

Javascript object 变量仅包含对对象的引用。这意味着您总是更新内存中的相同数据,并且您的数组包含对同一对象的 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);
    }
}

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);
        }
      }