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...

出于某种原因,下划线 find 返回未定义...

我究竟做错了什么?

4

2 回答 2

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;
        });
    }
};
于 2012-07-15T14:31:09.780 回答
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吗?它满足您所有的馆藏管理需求并使用 underscore 的方法。

// 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' });
于 2012-07-15T14:49:29.270 回答