简体   繁体   中英

How to get value of an object key from a Map

If I add these value on a Map:

var m = new Map();
m.set(1, "black");
m.set(2, "red");
m.set("colors", 2);
m.set({x:1}, 3);

m.forEach(function (item, key, mapObj) {
    document.write(item.toString() + "<br />");
});

document.write("<br />");
document.write(m.get(2));
document.write("<br />");
document.write(m.get({x:1}));

This prints:

black
red
2
3

red
undefined

Why I get undefined in the last line? And is there a way to retrieve the value of a object key stored in a Map?

You will probably need a reference to the object:

var m = new Map();
var o = {x:1};

m.set(o, 3);
m.get(o); //3

You need the object reference for getting the object. Any new literal is a new object, and is different.

 var obj = { x: 1 }, m = new Map(); m.set(1, "black"); m.set(2, "red"); m.set("colors", 2); m.set(obj, 3); m.forEach(function (item, key, mapObj) { console.log(item.toString()); }); console.log(m.get(2)); console.log(m.get(obj)); console.log([...m]); 

you have undefined simply because

document.write(m.get({x:1}));

the object you are fetching at this line is not the same as the one here

m.set({x:1}, 3);

try this:

var m = new Map();
var obj = {x:1};
m.set(1, "black");
m.set(2, "red");
m.set("colors", 2);
m.set(obj, 3);

m.forEach(function (item, key, mapObj) {
    document.write(item.toString() + "<br />");
});

document.write("<br />");
document.write(m.get(2));
document.write("<br />");
document.write(m.get(obj));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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