简体   繁体   English

如何从地图获取对象键的值

[英]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? 为什么我在最后一行中undefined And is there a way to retrieve the value of a object key stored in a Map? 有没有办法检索存储在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));

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

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