【问题标题】:Adding two different type of objects in array angular 5在数组 angular 5 中添加两种不同类型的对象
【发布时间】:2018-05-25 09:28:42
【问题描述】:

我有两个不同的数组,英雄: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
}

我什至不确定这是不是正确的方法?

【问题讨论】:

    标签: angular typescript components


    【解决方案1】:

    你的数组类型需要是HeroMonster的联合:

    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);
    

    【讨论】:

    • 谢谢你,编辑了我原来的帖子,因为我仍然缺少一些东西
    【解决方案2】:

    Heros 和Monsters 也是Participants,所以可以简单地说participantsParticipant 元素的数组。

    participants: Participant[] = [];
    

    【讨论】:

    • 所以我还需要我的 Participants 超级课程吗?
    • 是的。这显然不是唯一的解决方案,但在这种情况下使用继承是有意义的。
    猜你喜欢
    • 2021-07-03
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多