angular - 在数组 angular 5 中添加两种不同类型的对象
问题描述
我有两个不同的数组,英雄:Hero[] 和怪物:Monster[]。它们共享一个名为 totalInitiative 的公共字段。这两个数组需要放入同一个数组中,并根据它们的totalInitiative 进行排序。
我试图实现的目标是这样的:
Array[hero1, hero2, hero3, monster1, monster2]
我创建了一个名为 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{
}
我没有在 Participant 中添加公共字段,因为我有一个 Hero 和一个 Monster 组件,我需要这些公共属性来添加一个新的 Hero/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
}
我什至不确定这是正确的方法吗?
解决方案
您的数组的类型需要是Hero
和的联合Monster
:
const participants: (Hero | Monster)[] = [];
这是一个带有基本排序的缩减示例......
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);
推荐阅读
- c++ - oFx:使用 mouseEvent 初始化类实例
- mongoose - 猫鼬方法
- c# - NSubstitute 没有响应 Received() 断言
- visual-studio-code - 文件夹中大小写的更改不会反映在智能感知中
- python - 将 statsmodels.api 作为 sm 导入时出现意外错误
- php - 用于希伯来文文本的 utf8_encoding
- android - 空活动的 setContentView 上的 StrictMode 磁盘读取冲突
- .net - 从引用 netstandard 项目的旧式框架项目创建 nuget 包
- c++ - 从批次中提取矩阵,表示为张量
- javascript - javascript:调用默认函数?