JavaScript:如何将自定义 class 对象添加为数组的键

JavaScript: How do I add a custom class object as a key of an array

我用 属性 “名称”

创建了自定义 class

我还向 class 添加了一个函数,如果 2 个对象具有相同的名称,则 returns 为真。当我比较 2 个具有相同名称的自定义对象时,此函数有效。

但是,当我将这些自定义 class 对象作为键添加到 array/object 中时,我遇到了问题。

假设我的自定义 class 对象是一个。它也是数组中的键。当我将 a 与数组中的键进行比较时,我发现 a 不在数组中。

我的 class 构造函数:

class node {
  constructor(name) {
    this.name = name;
  }
  getname() {
    return this.name;
  }
  equiv(other) {
    return Boolean(this.name == other.name);
  }
  inarray(array) {
    for (let key in array) {
      if (this.name== key.name)
      {
        return true;
      }
    }
    return false;
  }
}

var a = new node("assss");
var b = new node("bssss");
var a2 = new node("assss");

var c = {a:1, b:2}

console.log( a.equiv(a2) ) // true
//But
console.log( a.inarray(c) ) // false

a.equiv(a2) returns true
但是
a.inarray(c) returns false

^ 这是我的问题

since you have upadated your question :

只是替换

if (this.name == key.name)

来自

if (this.name == key)

因为 key 是一个字符串(不是对象)并且它的值是 'a''b'
它们是 { a:1, b:2 }

的键

class node {
  constructor(name) {
    this.name = name;
  }
  getname() {
    return this.name;
  }
  equiv(other) {
    return Boolean(this.name == other.name);
  }
  inarray(array) {
    for (let key in array) {
      if (this.name == key)
      {
        return true;
      }
    }
    return false;
  }
}

var a  = new node("a")
  , b  = new node("b")
  , a2 = new node("a")
  , c  = { a:1, b:2 }
  ;
console.log( a.equiv(a2) ) // true
console.log( a.inarray(c) ) // true