我有一个库存类。在那个类中,我有2个函数,其中包含一系列项目。我想抓住两个阵列中的所有项目,然后将它们组合成一个单个数组,然后我用它来过滤掉项目。
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数组推入_lion字段,而无需在数组中插入数组?
答案 0 :(得分:2)
使用spread运算符,您可以使用push执行此操作,例如:
this._wolves.push(...wolves);
答案 1 :(得分:0)
似乎:
this._wolves = this._wolves.concat(wolves);
是一个很好的解决方案,使用concat可以抓取数组中的所有对象,将它们与另一个数组合并。但是如果你不这样做,它只会返回当前数组中的对象。