javascript - 从嵌套循环推送到数组的问题
问题描述
当我运行它时,除了阵列推送外,一切正常。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);
}
解决方案
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);
}
}
推荐阅读
- python - sklearn 内核语法中的常量是什么?
- sql - 如何摆脱多个branch_id?
- coq - sumbool 下的量化
- r - 如何将图例放在情节区域之外?
- php - 类 App\\Http\\Controllers\\Api\\v1\\panel\\StorageController 不存在
- jquery - 有没有办法让 jQuery 中只有一个函数处理所有 HTML 按钮?
- excel - 将新数据添加到 excel 列时如何更新 ComboBox 列表?
- flutter - 不确定如何编写 Flutter 测试来测试私有方法(测试 Flutter 的存储库)
- python - 过滤嵌套模型的查询集
- amazon-web-services - 如何跨资源类型将 AWS IP 列入白名单