Detailed Explanation of Map, Set, WeakMap, and WeakSet in JavaScript
Detailed Explanation of Map, Set, WeakMap, and WeakSet in JavaScript
Description
Map, Set, WeakMap, and WeakSet are four new data structures introduced in ES6, designed to address specific scenarios for data storage and manipulation needs. Compared to traditional objects and arrays, they exhibit significant differences in key/value types, performance characteristics, and memory management.
Knowledge Point Explanation
I. Map
- Basic Concept
- Map is a collection of key-value pairs, similar to an Object.
- However, keys can be of any type (objects, functions, primitives), whereas Object keys can only be strings or Symbols.
- Maintains insertion order of keys; iteration returns key-value pairs in the order they were inserted.
- Creation and Basic Operations
// Create a Map
const map = new Map()
// Add key-value pairs
map.set('name', 'John')
map.set(1, 'number one')
map.set({id: 1}, 'object key')
// Get a value
console.log(map.get('name')) // 'John'
// Check if a key exists
console.log(map.has(1)) // true
// Delete a key-value pair
map.delete('name')
// Get size
console.log(map.size) // 2
- Iteration Methods
const map = new Map([['a', 1], ['b', 2]])
// Iterate over key-value pairs
for (let [key, value] of map) {
console.log(key, value)
}
// Iterate over keys only
for (let key of map.keys()) {
console.log(key)
}
// Iterate over values only
for (let value of map.values()) {
console.log(value)
}
II. Set
- Basic Concept
- Set is a collection of values, similar to an Array.
- However, values are unique; duplicates are not allowed.
- Commonly used for array deduplication or existence checks for values.
- Creation and Basic Operations
// Create a Set
const set = new Set()
// Add values
set.add(1)
set.add(2)
set.add(2) // Duplicate value is ignored
// Check if a value exists
console.log(set.has(1)) // true
// Delete a value
set.delete(1)
// Get size
console.log(set.size) // 1
- Array Deduplication Application
const arr = [1, 2, 2, 3, 4, 4]
const uniqueArr = [...new Set(arr)]
console.log(uniqueArr) // [1, 2, 3, 4]
III. WeakMap
- Special Characteristics
- Keys must be of object type, not primitive types.
- Keys are weakly referenced; they do not prevent garbage collection.
- Not iterable; lacks
sizeproperty and iteration methods. - Often used for storing private data or metadata.
- Use Cases
let obj = {id: 1}
const weakMap = new WeakMap()
// Store private data
weakMap.set(obj, 'private data')
// When `obj` is garbage collected, the corresponding key-value pair is automatically removed.
obj = null // The corresponding entry in weakMap will be cleared during the next garbage collection.
IV. WeakSet
- Special Characteristics
- Values must be of object type.
- Values are weakly referenced; they do not prevent garbage collection.
- Not iterable; lacks
sizeproperty. - Often used for marking objects or checking if an object reference exists.
- Use Cases
const weakSet = new WeakSet()
let obj1 = {id: 1}
let obj2 = {id: 2}
weakSet.add(obj1)
weakSet.add(obj2)
console.log(weakSet.has(obj1)) // true
// When an object is garbage collected, it is automatically removed from the WeakSet.
obj1 = null
V. Comparison Summary of the Four Data Structures
| Feature | Map | Set | WeakMap | WeakSet |
|---|---|---|---|---|
| Key/Value Type | Any type | Any type | Objects only | Objects only |
| Iterable | Yes | Yes | No | No |
| Weak Reference | No | No | Yes | Yes |
| Garbage Collection Impact | None | None | Auto cleanup | Auto cleanup |
| Primary Use Case | Key-value storage | Value uniqueness | Metadata storage | Object tagging |
VI. Analysis of Practical Application Scenarios
- Suitable Scenarios for Map
- When non-string keys are needed.
- When key-value pairs need to maintain insertion order.
- Frequent addition and deletion of key-value pairs.
- Suitable Scenarios for WeakMap
- Storing private data associated with objects.
- Caching computed results.
- Associating data with DOM nodes.
// Example: Storing data associated with DOM nodes
const domData = new WeakMap()
const element = document.getElementById('myElement')
// Store data related to a DOM node
domData.set(element, {clickCount: 0})
// When the DOM node is removed, the associated data is automatically reclaimed.
Understanding the characteristics and appropriate scenarios for these data structures helps in selecting the most suitable tool to solve specific problems during development.