[英]JavaScript: How do I add a custom class object as a key of an array
I have created a custom class with the property “name”我创建了一个自定义 class 属性“名称”
I also added a function to the class which returns true if 2 objects have the same name.我还在 class 中添加了 function ,如果 2 个对象具有相同的名称,则返回 true。 This function works when I compare 2 custom objects with the same name.
当我比较两个同名的自定义对象时,这个 function 有效。
However, I am facing problems when I added these custom class objects as keys in an array/object.但是,当我将这些自定义 class 对象添加为数组/对象中的键时,我遇到了问题。
Suppose my custom class object is a.假设我的自定义 class object 是一个。 It is also a key in an array.
它也是数组中的一个键。 When I compare a with the keys in the array, I get that a is not in the array.
当我将 a 与数组中的键进行比较时,我发现 a 不在数组中。
My class constructor:我的 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.equiv(a2)
返回true
But但
a.inarray(c)
returns false
a.inarray(c)
返回false
^ this is my issue ^ 这是我的问题
since you have upadated your question:
因为你已经更新了你的问题:
just replace只需更换
if (this.name == key.name)
by经过
if (this.name == key)
because key
is a string (not an object) and it' values are 'a'
or 'b'
因为
key
是一个字符串(不是一个对象),它的值是'a'
或'b'
they are the keys of { a :1, b :2 }它们是 { 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.