首页 > 解决方案 > 如何查找在 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 类的实例?

标签: javascriptclassdictionary

解决方案


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

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"))));


推荐阅读