如何使用"getOwnPropertyNames"来遍历地图的内容 [英] how to use 'getOwnPropertyNames' to iterate through contents of a map

查看:35
本文介绍了如何使用"getOwnPropertyNames"来遍历地图的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的代码部分中张贴了地图.如图所示,我向地图添加了一些值.但是当我尝试使用来显示地图的内容时如代码中所示的"getOwnPropertyNames",循环中的log语句不显示任何内容.

I have the map posted below in the code section. I added some values to the map as shown.But when i tried to display the contents of the map using 'getOwnPropertyNames' as shown in th code, the log statement in the loop does not display any thing.

请让我知道如何正确使用'getOwnPropertyNames'

please let me know how to utilize 'getOwnPropertyNames' properly

代码:

const mymap = new Map();

const mapKeyToValue = (key, value) => {
  mymap.set(key, value);
};

const getMyMap = () => mymap;

mapKeyToValue('1', [{ 'a': 10, 'b': 100, 'c': 1000 }]);
mapKeyToValue('2', [{ 'a': 20, 'b': 200, 'c': 2000 }]);
mapKeyToValue('3', [{ 'a': 30, 'b': 300, 'c': 3000 }]);
mapKeyToValue('4', [{ 'a': 40, 'b': 400, 'c': 4000 }]);


console.log(Object.getOwnPropertyNames(mymap));//displays []

Object.getOwnPropertyNames(mymap).forEach( (v) => {
  console.log(mymap[v]);//displays nothing
});

推荐答案

地图不具有属性(该属性仅限于字符串和符号键).它将元素存储在内部.要遍历 Map ,使用其 entries values keys 或隐式迭代器方法以及 for…of 循环:

A map does not have properties (which would be limited to string and symbol keys). It stores its elements on the inside. To iterate through a Map, use its entries, values, keys, or implicit iterator methods with a for … of loop:

for (const [key, value] of mymap) {
    console.log(key, value);
}

这篇关于如何使用"getOwnPropertyNames"来遍历地图的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆