introduction
In JavaScript,Map
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 scenarios where key-value pairs are required to be frequently operated. This article will introduce in detailMap
creation, common methods, iterative methods, and discuss its differences from objects and practical application scenarios.
1. Create a Map
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. Comparison between Map and object
StudyingMap
Before the basic operations, 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 Attributes |
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. Common methods of Map
3.1 set(key, value)
Used toMap
Add a key-value pair. If the key already existsset
The 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 , returntrue
orfalse
。
(("name")); // Output true(("gender")); // Output false
3.4 delete(key)
Delete the specified key-value pair and returntrue
If it is successfully deleted, otherwise 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.
("name", "Alice"); ("age", 25); (); // Output 2
4. Map iterative method
Map
Supports multiple iteration 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 , each key-value pair will be[key, value]
Return in the form of .
for (let entry of ()) { (entry); } // Output:// [ 'name', 'Alice' ] // [ 'age', 25 ]
4.5 Use for...of to traverse Map
Can be used directlyfor...of
TraversalMap
, will be called by defaultentries()
method, therefore return[key, value]
array.
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, and
Map
You can use any data type 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 search, insert and delete 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 will be 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 key of the object may be affected
Influence, and
Map
There is no problem with prototype chain pollution, and any key can be stored safely.
6. Use Map to count the number of letters
We can use an example to compareMap
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: No Map, 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: Use Map
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. Introduction to WeakMap
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 will also be garbage collected, which can prevent memory leakage.
Features of WeakMap
- Only objects are accepted as keys and no primitive types are supported.
- Keys are weak references and do not prevent garbage collection.
- No
size
Attributes,clear
Methods and traversal methods (forEach
、keys
、values
、entries
), so it cannot be traversedWeakMap
。
Use scenarios
WeakMap
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 is garbage collected, and the key-value pairs in WeakMap will also be cleared
Summarize
Map
It is a powerful key-value pair data structure, with the advantages of 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 them.Map
!
This is all about this article about the usage of Map in JavaScript. For more related content on Map in JS, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!