简体   繁体   English

如何访问作为js Map中对象的键的值

[英]How to access values of keys that are objects in js Map

I am trying to store values in a JavaScript Map using an object as a key.我正在尝试使用对象作为键将值存储在 JavaScript 映射中。 However I am unable to access them using the get method provided by Map object.但是我无法使用 Map 对象提供的get方法访问它们。 This is what I am trying to do -这就是我想要做的 -

let map1 = new Map();
map1.set({a: 1}, "valueforobject");
console.log(map1.get({a: 1})); //expected this to print valueforobject but got undefined

When I am logging the map itself however I can the that the value has been stored safely.但是,当我记录地图本身时,我可以确定该值已安全存储。 How do I access this using the get method or any other way appropriate here?我如何使用 get 方法或任何其他合适的方式访问它?

This works.这有效。 Take a look at the official documentation .看看官方文档

let map1 = new Map();
let keyobj = {a: 1};
map1.set(keyobj, "valueforobject");
console.log(map1.get(keyobj)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM