Sunday, 21 October 2018

JavaScript: Map: clear(): Remove all the elements from map

‘clear’ method removes all the elements in the map.

HelloWorld.js
function printMap(map){
  console.log("***************************");
  console.log("Total elements in countriesMap are : " + map.size);
  for (var [country, capital] of map) {
    console.log(country + ' : ' + capital);
  }
  console.log("***************************");
}

var countries = [["Russia", "Moscow"], ["Spain", "Madrid"]];

var countriesMap = new Map(countries);

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

printMap(countriesMap);

console.log("\nClearing all the elements in countriesMap\n")
countriesMap.clear();

printMap(countriesMap);


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

Clearing all the elements in countriesMap

***************************
Total elements in countriesMap are : 0
***************************



Previous                                                 Next                                                 Home

No comments:

Post a Comment