SoFunction
Updated on 2025-03-10

Detailed explanation of map attribute example in JavaScript

In JavaScriptMapObjects save key-value pairs and are able to remember the original insertion order of keys

Here is how to use it in JavaScriptMapSummary of the blog post of the object:

1. Create and initialize Map objects

usenew Map()The constructor can create a new oneMapObject. You can also pass an iterable object (such as a key-value pair array) into the constructor to initializeMapObject.

const map1 = new Map(); // Create an empty Map objectconst map2 = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
]); // Initialize arrays using key-valueMapObject

2. Add and get key-value pairs

useset()Method toMapAdd key-value pairs to the object, useget()The method obtains the corresponding value according to the key.

('key1', 'value1');
('key2', 'value2');
(('key1')); // Output: 'value1'(('key2')); // Output:'value2'

3. Check whether the key exists

usehas()Method CheckMapWhether the specified key exists in the object.

(('key1')); // Output: true(('key3')); // Output:false

4. Delete key-value pairs

usedelete()Method fromMapDeletes the specified key and its corresponding value in the object.

('key1');
(('key1')); // Output:false

5. Iterate over Map objects

MapObjects supportforEach()Method orfor...ofLoop to traverse.

// Use the forEach() method to traverse((value, key) => {
  (`${key}: ${value}`);
});
// Loop through with for...offor (const [key, value] of map1) {
  (`${key}: ${value}`);
}

6. Comparison between Map objects and other data structures

MapObject andObjectandWeakMapOther data structures, etc., have some differences when storing key-value pairs. For example,MapThe object can remember the insertion order of the keys, andObjectThe order of attributes may vary across JavaScript engines. in addition,WeakMapOnly accept objects as keys, which makes it more important in certain scenariosMapObjects are more suitable.

7. Summary

MapObjects provide a flexible and efficient way to store key-value pairs in JavaScript. It has many practical methods, such asset()get()has()anddelete()etc., making it easier to operate and manage key-value pairs. also,MapObjects can also remember the insertion order of keys, which is very useful in some application scenarios.

This is all about this article about map attributes in JS. For more related map attribute content in js, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!