我希望能够将类实例设置为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());...what我要传递给.get(...)以引用类B的实例吗?
发布于 2019-12-13 02:11:55
在这种情况下,您必须传递完全相同的对象(因此,创建另一个具有相同内容的对象是不够的,因为您无法为该类提供自己的比较器,而内置的==/===会说它们是不同的):
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);
当然,也有==/===比较好的“东西”,例如字符串。如果你把你的key对象串起来(比如变成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"))));
https://stackoverflow.com/questions/59310164
复制相似问题