我正在尝试编写一个函数,1. 将一个项目添加到可观察数组中,2. 如果该项目已存在于数组中,则替换该项目
self.addNotification = function (name, availability, note) {
//see if we already have a line for this product
var matchingItem = self.notifications.indexOf(name);
if (matchingItem !== undefined) {
self.notifications.replace(self.notifications()[index(matchingItem)],
new Notification(self, name, availability, note));
}
else {
self.notifications.push(new Notification(self, name, availability, note));
}
};
我做错了什么?
问候安德斯
最佳答案
这是我的答案:fiddle
在 Chrome 中按 F12 或在 FireFox 中使用 FireBug 查看控制台日志输出。
var notifications = {
notifs: [],
updateNotifications: function(notification) {
'use strict';
var matchIndex;
for (matchIndex = 0; matchIndex < this.notifs.length; matchIndex += 1) {
if (this.notifs[matchIndex].name === notification.name) {
break;
}
}
if (matchIndex < this.notifs.length) {
this.notifs.splice(matchIndex, 1, notification);
} else {
this.notifs.push(notification);
}
}
};
notifications.updateNotifications({
name: 'John',
available: false,
note: "Huzzah!"
});
notifications.updateNotifications({
name: 'Jane',
available: true,
note: "Shazam!"
});
notifications.updateNotifications({
name: 'Jack',
available: true,
note: "Bonzai!"
});
notifications.updateNotifications({
name: 'Jane',
available: false,
note: "Redone!"
});
console.log(notifications);
关于javascript - 在可观察数组中添加和替换项目的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13020026/