2016-05-12 125 views
0

我有一个库存类。在那个类中,我有两个函数,其中包含一组项。我想抓住两个阵列中的所有物品,并将它们一起推入一个singel数组中,然后用它过滤出物品。将对象推入数组

class Inventory { 

    private _lions = []; 
    private _wolves = []; 
    private _allAnimals: Array<any> = []; 

    getAllLions(): void { 
     const lions: Array<ILion> = [ 
      { id: 1, name: 'Joffrey', gender: Gender.male, age: 20, price: 220, species: Species.lion, vertrabrates: true, warmBlood: true, hair: 'Golden', runningSpeed: 30, makeSound() { } }, 
      { id: 2, name: 'Tommen', gender: Gender.male, age: 18, price: 230, species: Species.lion, vertrabrates: true, warmBlood: true, hair: 'Golden', runningSpeed: 30, makeSound() { } }, 
      { id: 3, name: 'Marcella', gender: Gender.female, age: 24, price: 180, species: Species.lion, vertrabrates: true, warmBlood: true, hair: 'Golden', runningSpeed: 30, makeSound() { } }, 
     ]; 

     for (let lion of lions) { 
      this._lions.push(lion); 
     }   
    } 

    getAllWolves(): void { 
     const wolves: Array<IWolf> = [ 
      { id: 1, name: 'Jon', gender: Gender.male, price: 130, species: Species.wolf, age: 13, vertrabrates: true, warmBlood: true, hair: 'Grey', runningSpeed: 30, makeSound() { } }, 
      { id: 2, name: 'Robb', gender: Gender.male, price: 80, species: Species.wolf, age: 18, vertrabrates: true, warmBlood: true, hair: 'Black', runningSpeed: 30, makeSound() { } }, 
      { id: 3, name: 'Sansa', gender: Gender.female, price: 10, species: Species.wolf, age: 35, vertrabrates: true, warmBlood: true, hair: 'Grey', runningSpeed: 30, makeSound() { } }, 
      { id: 4, name: 'Arya', gender: Gender.female, price: 190, species: Species.wolf, age: 8, vertrabrates: true, warmBlood: true, hair: 'White', runningSpeed: 30, makeSound() { } }, 
     ]; 

     for (let wolf of wolves) { 
      this._wolves.push(wolf); 
     } 
    } 

    getAllAnimals(): void { 
     this._allAnimals = this._lions.concat(this._wolves); 
    }; 

    findByTemplate(template: any): Array<any> { 
     return this._allAnimals.filter(animal => { 
      return Object.keys(template).every(propertyName => animal[propertyName] === template[propertyName]); 
     }); 
    } 
} 

做为狮子和狼的数组上的循环工作,但我宁愿推动整个阵列的领域。但后来我在数组内引入一个数组,导致过滤函数出现问题。

是否有可能将狮子数组推入_lion字段,而不是将数组插入数组中?

回答

1

随着传播经营者可以使用推,像这样做:

this._wolves.push(...wolves); 
+0

你觉得有一个首选的方式来做到这一点?性能明智? –

+0

我不知道性能是否明智,但将_adds_项目推送到数组,而concat _returns一个新的array_。所以它可能取决于你是否想保持你的源数组,或改变它。 –

0

看来:

this._wolves = this._wolves.concat(wolves); 

是一个很好的解决方案,CONCAT它抓住从阵列中的所有对象与另一个阵列合并。但是,如果你不这样做,它只是返回当前数组中的对象。