首页 > 解决方案 > 从嵌套循环推送到数组的问题

问题描述

当我运行它时,除了阵列推送外,一切正常。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);
    }

标签: javascriptarraysfor-loopnested-loops

解决方案


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

推荐阅读