2012-07-15 94 views
0

我想用underscore.js實現某種hasObject函數。查找數組中的對象

例子:

var Collection = { 
    this.items: []; 
    this.hasItem: function(item) { 
     return _.find(this.items, function(existingItem) { //returns undefined 
      return item % item.name == existingItem.name; 
     }); 
    } 
}; 

Collection.items.push({ name: "dev.pus", account: "stackoverflow" }); 
Collection.items.push({ name: "margarett", account: "facebook" }); 
Collection.items.push({ name: "george", account: "google" }); 

Collection.hasItem({ name: "dev.pus", account: "stackoverflow" }); // I know that the name would already be enough... 

出於某種原因,強調尋找不確定的回報......

我在做什麼錯?

+8

究竟是什麼,你認爲'%'操作符呢? – Pointy 2012-07-15 14:19:18

+0

你說你想知道一個對象是否包含另一個對象,但是你似乎只是在判斷'name'屬性是否相同。那麼整個對象應該匹配還是僅僅是'name'屬性? – Utkanos 2012-07-15 14:20:39

+0

@Utkanos就像你在評論中看到的那樣,它只是測試這個名字,但是知道如何測試整個對象會很好 – 2012-07-15 15:56:02

回答

4

它看起來像你正在閱讀的文檔下劃線望文生義,在 他們有:

var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); 

然而,這並沒有任何意義了你的情況,你只是想看看是否.name屬性等於 其他一些對象的.name,像這樣:

var Collection = { 
    items: [], 

    hasItem: function(item) { 
     return _.find(this.items, function(existingItem) { //returns undefined 
      return item.name === existingItem.name; 
     }); 
    } 
}; 
0

你需要檢查這兩個值的名稱和賬號。

var Collection = { 
    this.items: []; 
    this.hasItem: function(target) { 
    return _.find(this.items, function(item) { 
     return item.name === target.name && item.acount === target.account; 
    }); 
    } 
}; 

您是否考慮過使用Backbone.js?它滿足您所有的收藏管理需求,並使用下劃線的方法。

// create a collection 
var accounts = new Backbone.Collection(); 

// add models 
accounts.add({name: 'dev.pus', account: 'stackoverflow'}); 
accounts.add({name: 'margarett', account: 'facebook'}); 
accounts.add({name: 'george', account: 'google'}); 

// getting an array. 
var results = accounts.where({ name: 'dev.pus', account: 'stackoverflow' });