如何查找在 Map JavaScript 中用作键的类实例?



我希望能够在 Map 中将类实例设置为键,然后能够查找它:

class A {
constructor() {
this.map = new Map();
}
addValue(value) {
if (value) {
const b = new B(value);
this.map.set(b, "Some value");
}
}
getMap() {
return this.map;
}
}
class B {
constructor(value) {
this.value = value;
}
getValue() {
return this.value;
}
}

所以如果我这样做...

const a = new A();
a.addValue("B");
// Now I want to print the value of the class B instance to the console - what do I pass in?
console.log(a.getMap().get(...).getValue());

。我应该传递给.get(...)什么来引用类 B 的实例?

在这种情况下,您必须传递完全相同的对象(因此创建另一个具有相同内容的对象是不够的,因为您无法为该类提供自己的比较器,并且内置==/===会说它们是不同的(:

class mykey {
constructor(something) {
this.something=something;
}
}
let map=new Map();
map.set(new mykey("hello"),"hellotest");
console.log("new key:",map.get(new mykey("hello")));
let key=new mykey("key");
map.set(key,"keytest");
console.log("reused key:",map.get(key));
let dupekey=new mykey("key");
console.log("==",key==dupekey);
console.log("===",key===dupekey);

当然,有些"东西"==/===比较得更好,例如字符串。如果你把关键对象串起来(比如成 JSON(,那会突然起作用:

class mykey {
constructor(something) {
this.something=something;
}
}
let map=new Map();
console.log(JSON.stringify(new mykey("hello")));
map.set(JSON.stringify(new mykey("hello")),"hellotest");
console.log(map.get(JSON.stringify(new mykey("hello"))));

最新更新