SoFunction
Updated on 2025-02-28

Usage and description of Map objects in JS

Map Objects in JS

Create map object

var map = new Map();

2. Put key-value pairs into map object

("key",value)
("key1",value1)
("key2",value2)

3. Get map value according to key

(key)

4. Delete the map specified object

delete map[key]

or

(key)

5. Loop through map

(function(key){
("key",key)  //The output is the value value in the map})

Map and normal objects in JS

Map Objects

Map object saves key-value pairs. Any value (object, array, string, numeric, boolean, null, undefined) can be used as a key or as a value.

A Map object is performed according to the order in which elements are inserted in the object are inserted during iterations — a for...of loop returns an array of form [key, value] after each iteration.

Object object

The Object constructor creates an object wrapper. The content is a pair of names (strings) and values ​​(any value), where the names are separated by colons and values.

Comparison of Objects and maps

Similar to Objects and Maps, they both allow you to access a value by pressing a key, delete a key, and detect whether a key is bound to a value. So (and there are no other built-in alternatives) we used to use objects as Maps. However, there are some important differences between Maps and Objects. Using Maps in the following situations is a better choice:

Map Object
Unexpected key Map does not contain any keys by default. Contains only explicitly inserted keys. An Object has a prototype, and the key names on the prototype chain may conflict with the key names you set on the object. Note: Although ES5 can start with (null) to create an object without prototypes, this usage is less common.
Key type A Map's key can be any value, including a function, object, or any primitive type. The key of an Object must be a String or Symbol.
The order of keys The keys in the map are ordered. Therefore, when iterating, a Map object returns the key value in the order of insertion. Note that a key of an Object is out of order: since the ECMAScript 2015 specification, objects have indeed preserved the order in which string and Symbol keys are created; therefore iterating on objects with only string keys will produce the keys in the insertion order.
Size The number of key-value pairs of Map can be easily obtained through the size attribute The number of key-value pairs of Object can only be calculated manually
Iteration Map is iterable, so it can be iterated directly. Iterating over an Object requires some way to get its key before it can iterate.
performance Better perform in scenarios where key-deletion value pairs are frequently added and deleted. No optimization was made in scenarios where key-value pairs were frequently added and deleted.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.