How to use a for loop statement in a map?

In a map, you can use the forEach method to iterate through key-value pairs. Below is an example code showing how to use a for loop statement in a map.

let myMap = new Map();

myMap.set('1', 'one');
myMap.set('2', 'two');
myMap.set('3', 'three');

for (let [key, value] of myMap) {
    console.log(`${key} = ${value}`);
}

In the example above, we first created a Map object called myMap, then added three key-value pairs to the Map using the set method. Next, we used a for loop statement and destructuring assignment to iterate through the key-value pairs in the Map, assigning the key and value to variables key and value respectively, and then printing them out.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds