Javascript 从嵌套循环推送到数组的问题
当我运行这个程序时,除了数组推送之外,其他一切都正常工作。console.lognotificationdata;显示通知数据正确更新了其值,但查看console.lognotifications我有7个相同的通知,其值与notificationdata中的最后一个值匹配。不知何故,推到阵列的操作没有正确进行,我似乎无法理解。有什么想法吗Javascript 从嵌套循环推送到数组的问题,javascript,arrays,for-loop,nested-loops,Javascript,Arrays,For Loop,Nested Loops,当我运行这个程序时,除了数组推送之外,其他一切都正常工作。console.lognotificationdata;显示通知数据正确更新了其值,但查看console.lognotifications我有7个相同的通知,其值与notificationdata中的最后一个值匹配。不知何故,推到阵列的操作没有正确进行,我似乎无法理解。有什么想法吗 var notifications = []; reminder.days.value = ["Monday", "Tuesday", "Wednesday"
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对象变量仅保存对对象的引用。这意味着您总是更新内存中的相同数据,并且您的数组包含对同一对象的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);
}
}
您可以尝试在中不使用const,这样时间和日期可能会改变。将其更改为let或just var。