如何实现Master细节类在javascript中查找函数?

问题描述:

我有这样的代码:如何实现Master细节类在javascript中查找函数?

function Item(id, itemType, itemData, itemCategoryId, itemRank) { 
    this.id = id; 
    this.itemType = itemType; 
    this.itemData = itemData; 
    this.itemCategoryId = itemCategoryId; 
    this.itemRank = itemRank; 
} 
function Category(id) { 
    this.id = id; 
} 

,我希望写的项目类中的函数,我给它的CategoryId,它将返回的所有项目与此类别ID对象,
最新最好的办法去做?

我看不出有任何阵列....

我会假设会有一个项目的原型(note that there are no classes in javascript),它会是这个样子:

function Item(id, categoryId, data, rank) { 
    this.id = id; 
    this.categoryId = categoryId; 
    this.data = data; 
    this.rank = rank; 
} 

function Items() { 
    this.items = []; 
    this.findByCategory = function(categoryId) { 
    var result = []; 
    for(var i=0;i<this.items.length;i++) { 
     if (categoryId == this.items[i].categoryId) 
      result.push(this.items[i]); 
    } 
    return result; 
    } 
    this.add = function(id, categoryId, data, rank) { 
    this.items.push(new Item(id, categoryId, data, rank)); 
    } 
} 

var items = new Items(); 
items.add(2, 0, null, null); 
items.add(1, 1, null, null); // I'm not going to care about data and rank here 
items.add(2, 1, null, null); 
items.add(3, 1, null, null); 
items.add(4, 2, null, null); 
items.add(5, 3, null, null); 

var cat1 = items.findByCategory(1); 
alert(cat1); // you will get a result of 3 objects all of which have category 1