The use of Map in JavaScript

Another new data structure in ES6 is Map, which is used to store mapping relationships .

We can use objects to store mapping relationships before ES6, so do we still need Map?

  • In fact, the object storage mapping relationship can only use strings (and ES6's new Symbol ) as attribute names (keys);
  • Sometimes we may want to use other types such as objects as keys . At this time, the objects will be automatically converted into strings as keys.
      const obj1 = {
        name:"key"
      }
      const map = new Map()
      map.set(obj1,"这个是value")
      console.log(map.get(obj1))

Create a Map object, use set to use the object obj1 as the key, and use get to get the value corresponding to obj1.

const map1 = new Map([
        [obj1, "abc"],
        [obj2, "abc"],
        [obj3, "abc"],
      ])
      console.log(map1.get(obj1));
      console.log(map1.get(obj2));
      console.log(map1.get(obj3));

Common methods of Map

Common properties of Map

  • size: returns the number of elements in the Map;

Common methods of Map:

  • set(key, value): add key and value to the Map, and return the entire Map object;
  • get(key): Get the value in the Map according to the key;
  • has(key): Determine whether a certain key is included, and return the Boolean type;
  • delete(key): Delete a key-value pair according to the key and return the Boolean type;
  • clear(): clear all elements; forEach(callback, [, thisArg]): traverse the Map through forEach;

Map can also be traversed through for of.

Another data structure of the Map type is called WeakMap, which also exists in the form of key-value pairs.

So what is the difference with Map?

  • Difference 1: The key of WeakMap can only use objects, and does not accept other types as keys;
  • Difference 2: The key of the WeakMap thinks that the reference to the object is a weak reference. If there is no other reference to this object, then the GC can recycle the object;

There are four common methods of WeakMap:

  • set(key, value): add key and value to the Map, and return the entire Map object;
  • get(key): Get the value in the Map according to the key;
  • has(key): Determine whether a certain key is included, and return the Boolean type;
  • delete(key): Delete a key-value pair according to the key and return the Boolean type;

Guess you like

Origin blog.csdn.net/m0_51636525/article/details/125467510