Thursday, April 12, 2018

Important methods in Map with example

Map is like key value pair concept (like an Object). But Map allows keys as any type. Remember object allows only string key.

Note: ES6 map is different. Do not make confuse yourself.

Main methods are below,

      new Map() – creates the map.

     map.set(key, value) – stores key and value.

     map.get(key) – returns the value by the key. Suppose If key doesn’t exist undefined will be  returned.

     map.has(key) – returns true if the key exists, else false will be returned.

     map.delete(key) – removes the value by the key.

     map.clear() – clears the map.

     map.size – returns the current element count.

Simple Example I:



let map = new Map();

map.set('1', 'stringOne');   // a string key
map.set(1, 'number1');     // a numeric key
map.set(true, 'booleanValueTrue'); // a boolean key

alert( map.get(1)   ); // 'number1'
alert( map.get('1') ); // 'stringOne'
alert( map.get(true) ); // 'booleanValueTrue
alert( map.size ); // 3


Note: See the above example, Keys are not converted to string.





No comments:

Post a Comment