A map can store key-value pairs with any data type for the keys.
The keys’ original placement order is retained by a Map.
Method | Description |
Map() | Creates a new Map object. |
clear() | Removes all key/value pairs from the Map object. |
delete(key) | Removes the key/value pair with the specified key. |
entries() | Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order. |
forEach((value, key, map) => {…}) | Calls a function for each key/value pair in the Map object. |
get(key) | Returns the value associated to the key, or undefined if there is none. |
has(key) | Returns a boolean indicating whether an element with the specified key exists or not. |
keys() | Returns a new Iterator object that contains the keys for each element in the Map object in insertion order. |
set(key, value) | Sets the value for the key in the Map object. Returns the Map object. |
values() | Returns a new Iterator object that contains the values for each element in the Map object in insertion order. |
Example code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script type="text/javascript"> const map = new Map(); map.set('firstName', 'John'); map.set('lastName', 'Doe'); map.set('age', 30); console.log(map.get('firstName')); // 'John' console.log(map.has('email')); // false </script> </body> </html> |
Console Output:
John
false