마스터 세부 사항 클래스를 구현하는 방법 JavaScript에서 기능을 찾는 방법은 무엇입니까?

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

그리고 카테고리 ID를 제공하는 항목 클래스에 대한 함수를 작성하고 싶습니다.이 카테고리 ID로 모든 항목 객체를 반환합니다.
그렇게하는 가장 좋은 방법은 무엇입니까?

도움이 되었습니까?

해결책

배열이 없습니다 ....

항목 프로토 타입이 있다고 가정합니다 (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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top