SoFunction
Updated on 2025-04-06

Map usage guide in JavaScript

A complete guide to Map in JavaScript

introduction

In JavaScript,MapIt is a data structure for storing key-value pairs, with flexible key types and rich methods. Compared with traditional objects,MapIt 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. MapComparison with objects

StudyingMapBefore the basic operation, let's take a look atMapDifference 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 sizeproperty 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 thatMapThere are significant advantages in key type, insertion order, and key-value pair operation efficiency.

3. MapCommon methods

3.1 set(key, value)

Used toMapAdd a key-value pair. If the key already existssetIts 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)

examineMapWhether the specified key exists in it, returntrueorfalse

(("name")); // Output true(("gender")); // Output false

3.4 delete(key)

Delete the specified key-value pair and returntrueIf 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

returnMapThe number of key-value pairs in the middle.

("name", "Alice");
("age", 25);
(); // Output 2

4. MapIterative method

MapSupports multiple iterative methods, allowing you to easily traverse key-value pairs.

4.1 forEach(callback)

TraversalMapEach key-value pair incallbackThe function accepts three parameters: value, key, and Map itself.

((value, key) => {
  (`${key}: ${value}`);
});
// Output:// name: Alice
// age: 25

4.2 keys()

returnMapIterator for all keys in (Iterator), can be usedfor...ofCome and traverse.

for (let key of ()) {
  (key);
}
// Output:// name
// age

4.3 values()

returnMapIterator for all values ​​in (Iterator)。

for (let value of ()) {
  (value);
}
// Output:// Alice
// 25

4.4 entries()

returnMapIterators 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...ofTraversalMap

Can be used directlyfor...ofTraversalMap, 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. MapApplication scenarios

MapIt 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,MapAny 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 pairsMapIt 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 orderMapKey-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 affectedInfluence, andMapThere is no prototype chain pollution problem, any key can be stored safely.

6. UseMapStatistics the number of letters appearing

We can compare and use an exampleMapand not usedMapThe difference. Suppose we have a string that needs to count the number of times each letter appears.MapVery 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. WeakMapIntroduction

WeakMapyesMapA 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 isWeakMapThe keys of the keys will also be garbage collected, which can prevent memory leakage.

  • WeakMapFeatures: Only objects are accepted as keys and do not support basic types.
  • Keys are weak references and do not prevent garbage collection.
  • Nosizeproperty,clearMethods and traversal methods (forEachkeysvaluesentries), so it cannot be traversedWeakMap

Use scenarios

WeakMapIt 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

MapIt 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. andWeakMapIt 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!