gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:38:48 26 4
gpt4 key购买 nike

当我运行此命令时,除了数组推送之外,一切正常。 console.log(notificationdata);显示通知数据的值已正确更新,但查看 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);
}

最佳答案

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

关于javascript - 从嵌套循环推送到数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60424202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com