A complete guide to Map in JavaScript
introduction
In JavaScript,Map
It is a data structure for storing key-value pairs, with flexible key types and rich methods. Compared with traditional objects,Map
It provides a more efficient key-value pair operation method, which is especially suitable for handling large amounts of data and requires frequent operation of key-value pairs. This article will introduce in detailMap
, common methods, iterative methods, and explore the differences between it and object and practical application scenarios.
1. CreateMap
usenew Map()
To create an emptyMap
。
const map = new Map();
It can also be initialized at creation timeMap
, pass in an array containing key-value pairs:
const map = new Map([ ["name", "Alice"], ["age", 25] ]); (map); // Output Map(2) { 'name' => 'Alice', 'age' => 25 }
2. Map
Comparison with objects
StudyingMap
Before the basic operation, let's take a look atMap
Difference from traditional objects.
characteristic | Map |
Object |
---|---|---|
Key type | Any type (strings, objects, functions, etc.) | Can only be a string or symbol |
Insert order | Keep insertion order | Insert order is not guaranteed |
Number of key-value pairs |
size property |
Manual calculation (().length ) |
Prototype chain pollution | none | Yes, inheritance
|
Applicable scenarios | Frequent operation of key-value pairs, large amount of data | Small-scale key-value pairs or when a method is needed |
By comparison, we can see thatMap
There are significant advantages in key type, insertion order, and key-value pair operation efficiency.
3. Map
Common methods
3.1 set(key, value)
Used toMap
Add a key-value pair. If the key already existsset
Its value will be updated.
("name", "Bob"); ("age", 30); (map); // Output Map(2) { 'name' => 'Bob', 'age' => 30 }
3.2 get(key)
Get the value of the specified key. If the key does not exist, returnundefined
。
(("name")); // Output 'Bob'(("gender")); // Output undefined
3.3 has(key)
examineMap
Whether the specified key exists in it, returntrue
orfalse
。
(("name")); // Output true(("gender")); // Output false
3.4 delete(key)
Delete the specified key-value pair and returntrue
If deleted successfully, returnfalse
。
("age"); (map); // Output Map(1) { 'name' => 'Bob' }
3.5 clear()
ClearMap
, delete all key-value pairs.
(); (map); // Output Map(0) {}
3.6 size
returnMap
The number of key-value pairs in the middle.
("name", "Alice"); ("age", 25); (); // Output 2
4. Map
Iterative method
Map
Supports multiple iterative methods, allowing you to easily traverse key-value pairs.
4.1 forEach(callback)
TraversalMap
Each key-value pair incallback
The function accepts three parameters: value, key, and Map itself.
((value, key) => { (`${key}: ${value}`); }); // Output:// name: Alice // age: 25
4.2 keys()
returnMap
Iterator for all keys in (Iterator
), can be usedfor...of
Come and traverse.
for (let key of ()) { (key); } // Output:// name // age
4.3 values()
returnMap
Iterator for all values in (Iterator
)。
for (let value of ()) { (value); } // Output:// Alice // 25
4.4 entries()
returnMap
Iterators for all key-value pairs in the[key, value]
return in the form.
for (let entry of ()) { (entry); } // Output:// [ 'name', 'Alice' ] // [ 'age', 25 ]
4.5 Usefor...of
TraversalMap
Can be used directlyfor...of
TraversalMap
, will be called by defaultentries()
method, so it will return[key, value]
array of .
for (let [key, value] of map) { (`${key}: ${value}`); } // Output:// name: Alice // age: 25
5. Map
Application scenarios
Map
It is a structure suitable for storing key-value pairs, especially suitable for the following scenarios:
Need to use non-string keys: The key of an object can only be a string or symbol,Map
Any data type can be used as keys, such as objects, functions, etc.
const objKey = { id: 1 }; const map = new Map(); (objKey, "Object as key"); ((objKey)); // Output 'Object as key'
-
Need to operate frequently on key-value pairs:
Map
It performs better than objects in the search, insertion and deletion of key-value pairs, and is suitable for use in scenarios where key-value pairs are frequently operated. -
Need to keep the insertion order:
Map
Key-value pairs are stored in the order of insertion, so the order is fixed during traversal, while objects do not guarantee the insertion order. -
Avoid prototype chain contamination: The object's key may be affected
Influence, and
Map
There is no prototype chain pollution problem, any key can be stored safely.
6. UseMap
Statistics the number of letters appearing
We can compare and use an exampleMap
and not usedMap
The difference. Suppose we have a string that needs to count the number of times each letter appears.Map
Very suitable for this kind of key-value pair storage scenario.
Method 1: NoMap
, use normal objects
function countLettersWithObject(str) { const letterCounts = {}; // Use object to store the number of letters for (let letter of str) { if (letterCounts[letter]) { letterCounts[letter]++; } else { letterCounts[letter] = 1; } } return letterCounts; } const result = countLettersWithObject("hello world"); (result); // Output: { h: 1, e: 1, l: 3, o: 2, w: 1, r: 1, d: 1 }
Method 2: UseMap
function countLettersWithMap(str) { const letterCounts = new Map(); // Use Map to store the number of letters for (let letter of str) { if ((letter)) { (letter, (letter) + 1); } else { (letter, 1); } } return letterCounts; } const resultMap = countLettersWithMap("hello world"); (resultMap); // Output: Map(7) { 'h' => 1, 'e' => 1, 'l' => 3, 'o' => 2, 'w' => 1, 'r' => 1, 'd' => 1 }
7. WeakMap
Introduction
WeakMap
yesMap
A special type of , whose key must be an object and a weak reference (that is, it will not prevent the object from being garbage collected). If an object is no longer referenced elsewhere, then even if it isWeakMap
The keys of the keys will also be garbage collected, which can prevent memory leakage.
-
WeakMap
Features: Only objects are accepted as keys and do not support basic types. - Keys are weak references and do not prevent garbage collection.
- No
size
property,clear
Methods and traversal methods (forEach
、keys
、values
、entries
), so it cannot be traversedWeakMap
。
Use scenarios
WeakMap
It is usually used for storage of private attributes or private data, and it is not expected that this data affects garbage collection. It is suitable for temporary mapping relationships between objects and is used without traversal of data.
const weakMap = new WeakMap(); let obj = { id: 1 }; (obj, "some value"); ((obj)); // Output 'some value'obj = null; // Delete other references to the object// After this,obj Being recycled by garbage,WeakMap The key-value pairs in the
Summarize
Map
It is a powerful key-value pair data structure with flexible key type support, maintaining insertion order, and rich built-in methods. It is suitable for storing and operating a large number of key-value pairs. andWeakMap
It is a weak reference to object keysMap
, helps manage memory in specific scenarios. I hope these contents can help you fully understand and apply themMap
!
This is the article about the Map Usage Guide in JavaScript. For more related content on using js map, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!