كيفية تنفيذ تفاصيل ماستر الطبقات تجد وظيفة في جافا سكريبت؟

StackOverflow https://stackoverflow.com/questions/801888

  •  03-07-2019
  •  | 
  •  

سؤال

ولدي هذا الرمز:

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

وأريد أن أكتب وظيفة لفئة البند الذي أعطيها معرف_الفئة وسيعود جميع العناصر الكائنات مع هذه الفئة الهوية،
ما أفضل طريقة للقيام بذلك؟

هل كانت مفيدة؟

المحلول

وأنا لا أرى أي مجموعة ....

وأود أن نفترض أنه سيكون هناك نموذج وحدات (<م> <وأ href = "http://www.javaranch.com/journal/2008/10/Journal200810.jsp#a1" يختلط = "نوفولو noreferrer" > ملاحظة أنه لا توجد دروس في جافا سكريبت )، وأنها تبدو شيء مثل هذا:

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top