2012-10-22 107 views
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)); 
    } 
}; 

什麼時在存在功能我做錯了?

問候安德斯

回答

1

這裏是我的回答:fiddle

命中F12在Chrome或使用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);​ 
1

好,Array.prototype.indexOf永遠不會返回undefined。它可以是-1找不到),也可以是任何以0開頭的數字作爲數組索引。

+0

好的,謝謝,我已將undefined更改爲-1 ...但它只是不斷添加項目到數組。 – mupersan82