Javascript 用于在可观察数组中添加和替换项的函数

Javascript 用于在可观察数组中添加和替换项的函数,javascript,knockout.js,Javascript,Knockout.js,我正在尝试写一个函数,这个函数是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 !== und

我正在尝试写一个函数,这个函数是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));
    }
};
我做错了什么


对于Anders来说,
Array.prototype.indexOf
永远不会返回
未定义的
。它要么是
-1
(未找到),要么是数组索引中以
0
开头的任何数字。

以下是我的答案:

在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);​
var通知={
通知:[],
更新通知:功能(通知){
"严格使用",;
var匹配指数;
对于(matchIndex=0;matchIndex
好的,谢谢,我已将未定义更改为-1。。。但它只是不断地向数组中添加项。