2016-05-12 156 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它抓住從陣列中的所有對象與另一個陣列合併。但是,如果你不這樣做,它只是返回當前數組中的對象。