0

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

私は何を間違っていますか?

よろしくアンダース

4

2 に答える 2

1

まあ、Array.prototype.indexOf戻ってこないundefined。その-1( not found0 ) または配列インデックスの で始まる任意の番号。

于 2012-10-22T21:18:25.830 に答える
1

これが私の答えです: フィドル

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);​
于 2012-10-22T22:16:38.523 に答える