[英]Adding two different type of objects in array angular 5
I have two different arrays, heroes: Hero[] and monsters: Monster[]. 我有两个不同的数组,英雄:Hero []和怪物:Monster []。 They share a common field, named totalInitiative.
它们共享一个共同的字段,名为totalInitiative。 These two arrays need to be put into the same array and sorted on their totalInitiative.
这两个数组需要放入同一数组中,并按它们的totalInitiative进行排序。
The goal I'm trying to achieve is something like this: 我要达到的目标是这样的:
Array[hero1, hero2, hero3, monster1, monster2]
I created a superclass called Participant: 我创建了一个称为参与者的超类:
import {Participant} from './participant';
export class Hero extends Participant{
id: number;
name: string;
player: string;
hitPoints: number;
armor: number;
initModif: number;
imageUrl: string;
totalInitiave: number;
}
import {Participant} from './participant';
export class Monster extends Participant{
id:number;
name: string;
hitPoints: number;
armor: number;
initModif: number;
imageUrl: string;
}
export class Participant{
}
I did not add the common fields in Participant because I have a Hero and a Monster component where I need those common properties to add a new Hero/Monster. 我没有在“参与者”中添加公共字段,因为我有一个Hero和Monster组件,我需要这些公共属性来添加新的Hero / Monster。
Now I need to adjust my Encounter model so it consists of a Participant[] which holds the Hero[] and Monster[] 现在,我需要调整我的Encounter模型,使其包含一个拥有Hero []和Monster []的Participant []
import {Hero} from './hero';
import {Monster} from './monster';
import {Participant} from './participant';
export class Encounter {
id: number;
name: string;
participants: Participant[ Hero[] Monster[]]; //Doesn't work
}
I'm not even sure that this is the correct way? 我什至不确定这是正确的方法吗?
The type of your array needs to be a union of Hero
and Monster
: 数组的类型必须是
Hero
和Monster
:
const participants: (Hero | Monster)[] = [];
Here is a cut down example with a rudimentary sort... 这是一个简单的示例,种类繁多...
class Hero {
constructor(public initiative: number) { };
}
class Monster {
constructor(public initiative: number) { };
evil = 5;
}
const heroes = [
new Hero(5),
new Hero(3)
];
const monsters = [
new Monster(2),
new Monster(7)
];
const participants: (Hero | Monster)[] = heroes.concat(monsters);
const sorted = participants.sort((a, b) => a.initiative - b.initiative);
console.log(sorted);
Hero
和Monster
也是Participant
,因此您可以简单地说participants
是一组Participant
元素。
participants: Participant[] = [];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.