1.11 Common JavaScript libraries: Map and Set
Map
A Map object holds key-value pairs.
- Use
for...of
orforEach
can be traversed in insertion order. - Key-values can be anything, including functions, objects, or any primitive type.
Commonly used APIs:
- set(key, value): Insert a key-value pair, if the key already exists, the original value will be overwritten
- get(key): Find the keyword, if it does not exist, return undefined
- size: returns the number of key-value pairs
- has(key): returns whether the keyword key is included
- delete(key): delete the keyword key
- clear(): delete all elements
Set
Set objects allow you to store unique values of any type, whether primitive values or object references.
- Use
for...of
orforEach
can be traversed in insertion order.
Commonly used APIs:
- add(): add elements
- has(): Returns whether an element is contained
- size: returns the number of elements
- delete(): delete an element
- clear(): delete all elements