javascript - 如何查找在 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"))));
推荐阅读
- python - 如何合并 2 个字典列表,以便始终替换具有 None 值的键(如果不存在 None 值)
- html - 如何根据设备更改按钮大小?
- javascript - ReactJS - 在同一个 div 中更新组件(从列表生成)
- javascript - 检查输入表单需要两次点击才能验证
- android - 从 Firebase 子值读取的 Android Spinner 选定值
- c# - 如何通过 C# 中的事件处理程序将类的实例传回
- android - LocationManager 的 Criteria.POWER_LOW 的含义
- python - 当我尝试注销时显示找不到页面 (404)
- angular - 大型项目中的重新编译时间缓慢
- javascript - 在 Vue 中的 $router.go 之后执行函数