Sunday 21 October 2018

JavaScript: Map.prototype.keys(): Get all the keys of map

Map.prototype.keys()
This method returns an iterator, that contains all the keys of map.

  var keys = map.keys();
 
  for(var key of keys){
    console.log(key + " : " + map.get(key));
  }

Find the below working application.

HelloWorld.js
function printMap(map){
  console.log("***************************");
  console.log("Total elements in countriesMap are : " + map.size);
  
  var keys = map.keys();
  
  for(var key of keys){
    console.log(key + " : " + map.get(key));
  }
}

var countriesMap = new Map();

countriesMap.set("Bahrain", "Manama");
countriesMap.set("Cameroon", "Yaounde");
countriesMap.set("Norway", "Oslo");
countriesMap.set("India", "New Delhi");
countriesMap.set("Russia", "Moscow");
countriesMap.set("Spain", "Madrid");

printMap(countriesMap);

Output
***************************
Total elements in countriesMap are : 6
Bahrain : Manama
Cameroon : Yaounde
Norway : Oslo
India : New Delhi
Russia : Moscow
Spain : Madrid

Previous                                                 Next                                                 Home

No comments:

Post a Comment