簡體   English   中英

如何查找在 Map JavaScript 中用作鍵的類實例?

[英]How to look up class instance that is used as a key in a 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"))));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM