Site icon i2tutorials

Javascript-Map

Javascript-Map

 

The Map object holds key-value pairs and recalls the original insertion order of the keys. Any values both primitive values and objects may be used as either a key or a value.

This Map object iterates elements in insertion order wise. A for…of loop written an array of [key, value] for every iteration.

 

Syntax:

 

array.map(function(currentValue, index, arr), thisValue)

 

Note: this map() method does not change the original array.

 

Methods and properties are:

 

 

For instance:

 

<!DOCTYPE html>
<script>
"use strict";globalThis.__codeBoxId = "10tnj9teb5";

let map = new Map();

map.set('1', 'str1');   // a string key
map.set(1, 'num1');     // a numeric key
map.set(true, 'bool1'); // a boolean key

// remember the regular Object? it would convert keys to string
// Map keeps the type, so these two are different:
alert( map.get(1)   ); // 'num1'
alert( map.get('1') ); // 'str1'

alert( map.size ); // 3
</script>

 

Map can also use objects as keys:

 

<!DOCTYPE html>
<script>
"use strict";globalThis.__codeBoxId = "57p59bsvvb";

let john = { name: "John" };

// for every user, let's store their visits count
let visitsCountMap = new Map();

// john is the key for the map
visitsCountMap.set(john, 123);

alert( visitsCountMap.get(john) ); // 123
</script>

 

Iteration over Map:

 

There are 3 methods:

  1. keys() – iterable for keys,
  2. values() – iterable for values,
  3. entries() – iterable for entries [key, value]. It’s used by default in for..of.

 

For instance:

 

<!DOCTYPE html>
<script>
"use strict";globalThis.__codeBoxId = "df4ipdfkim";

let recipeMap = new Map([
 ['cucumber', 500],
 ['tomatoes', 350],
 ['onion',    50]
]);

// iterate over keys (vegetables)
for (let vegetable of recipeMap.keys()) {
 alert(vegetable); // cucumber, tomatoes, onion
}

// iterate over values (amounts)
for (let amount of recipeMap.values()) {
 alert(amount); // 500, 350, 50
}

// iterate over [key, value] entries
for (let entry of recipeMap) { // the same as of recipeMap.entries()
 alert(entry); // cucumber,500 (and so on)
}
</script>

 

Exit mobile version