问题
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.
please let me know how to utilize 'getOwnPropertyNames' properly
code:
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
});
回答1:
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);
}
来源:https://stackoverflow.com/questions/47670143/how-to-use-getownpropertynames-to-iterate-through-contents-of-a-map