Javascript Angular2+,检查数组中是否存在具有类定义的值

Javascript Angular2+,检查数组中是否存在具有类定义的值,javascript,angular,typescript,Javascript,Angular,Typescript,打字稿: heroes = [ new Hero('Windstorm', 1), new Hero('Bombasto', 13), new Hero('Magneta', 15), new Hero('Tornado', 22) ]; add(val: string) { if (val && !this.heroes.includes(new Hero(val))) { alert(this.heroes.includes(

打字稿:

heroes = [
    new Hero('Windstorm', 1),
    new Hero('Bombasto', 13),
    new Hero('Magneta', 15),
    new Hero('Tornado', 22)
  ];

add(val: string) {
  if (val && !this.heroes.includes(new Hero(val))) {
    alert(this.heroes.includes(new Hero(val)));
    this.heroes.push(new Hero(val));
  }
}

export class Hero {
  constructor(
    public name: string,
    public id?: number
  ) { }
}
Html:

我想创建一个add按钮,用于检查值是否存在于类Hero中的数组名中,如果存在,则不添加它。仅当键入的字符串在键名数组中不存在时才添加该字符串。

您不能像这样使用包含,因为它将在数组中查找确切的对象,而由于您刚刚创建了该对象,它将永远找不到该对象。您需要按值进行检查。一种方法是查看英雄中是否有特定的名字:

add(val: string) {
  // it is not the case that some heroes are named val
  if (val && !this.heroes.some(hero => hero.name === val )) {
    this.heroes.push(new Hero(val));
  }
}

这假设每个英雄都应该有一个唯一的名字。如果希望允许数组中有重复名称的英雄,则需要一些定义唯一性的其他属性,如唯一ID。

可以使用findIndex检查数组中是否存在该元素

    add(value:string) {

       if (this.heros.findIndex(x => x.name === value) === -1) {
        this.heroes.push(new Hero(value));
     } 
  }
    add(value:string) {

       if (this.heros.findIndex(x => x.name === value) === -1) {
        this.heroes.push(new Hero(value));
     } 
  }