It’s the end of the year, we’ve all gone home for Chinese New Year, so it’s time to talk about someone. Today we are going to talk about Map and WeakMap. Let’s start with a brief introduction to these two objects:

  • MapKey can be any type of value,ObjectCan only be string and Symbols.
  • MapThe instance stores data in the order in which it was inserted
  • MapInstance properties are easier to delete
  • WeakMapCompared with theMapProvides a better garbage collection mechanism

Let’s get down to business.

What is the Map

Take a look at MDN explanation:

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

Key words: key-value pairs, insertion order, key or value can be any type of data.

grammar

new Map([iterable])

Let’s look again at the properties and methods on the Map instance.

Initialize a Map instance:

const map = new Map(a);/ / empty Map
map.set(1."first");
map.get(1); // 'first'

const newMap = new Map([[1."zhangsan"],
  [2."lisi"]]); newMap.get(1); // "zhangsan"
newMap.get(2); // "lisi"
Copy the code

The key value

The key value in the object can only be a string. A Map instance can be any type of data as explained above.

const obj = {};

obj[1] = "one";
obj["1"]; // one
obj[1]; // one

const map = new Map(a); map.set(1."one");
map.set("1"."another one");
// Map contains 2 key-value pairs: 1, 'one' and '1', 'another one'
Copy the code

Again, Map instances use sameValueZero’s rule when comparing key names, somewhat like strictly equal ===, but with two exceptions: NaN and NaN, +0 and -0, which Map considers the same.

In addition, Map instances also support chained calls to set key-value pairs, and objects can only set one key-value pair at a time:

const map = new Map(a); map .set(1."one")
  .set(2."two")
  .set(3."three");
Copy the code

Delete the properties

Deleting an attribute value on an object will always return true unless the attribute value is

When deleting an attribute from a Map, return true if the attribute exists and false if it does not.

// Delete object properties
const obj = {
  name: "zhangsan"
};

delete obj.name; // true
delete obj.age; // true, if this attribute does not exist, it will also return true

// Delete the Map attribute
const map = new Map(a); map.set("name"."zhangsan");
map.delete("name"); // true
map.delete("age"); // false
Copy the code

What if you delete all the properties on the object? Maybe:

const obj = { 1: 234 };

obj = {};
Copy the code

But in this case, you are just copying a new empty object to the instance, and the old object is not necessarily deleted (depending on the garbage collection mechanism), as long as it is referenced elsewhere, it will remain.

for (let key in obj) {
  if (obj.hasOwnProperty(key)) {
    deleteobj[key]; }}Copy the code

A Map instance handles this nicely: map.clear(); .

traverse

As explained at the beginning of MDN, Map traversal is more predictable.

const obj = {};

obj[5] = "five";
obj[4] = "four";
Object.entries(obj); // [ ['4', 'four'], ['5', "five"] ]

const map = new Map(a); map .set(5."five")
  .set(4."four")
  .entries(); // [ 5 => "five", 4 => "four" ]
Copy the code

Like objects, maps have three methods for traversing objects:

  • map.keys()Returns an array of key names
  • map.values()Returns an array of key values
  • map.entries()Returns a traversable array containing a set of group key-value pairs

transformation

The Map constructor takes an array or iterable Object, so we can use the Object.entries method to transfer objects to Map instances:

const obj = {
  one: 1.two: 2
};

const map = new Map(Object.entries(obj));

console.log(map.get("one")); / / 1
Copy the code

How do you turn a Map instance into an object? Fortunately, we have the object. fromEntries method, which uses the opposite of object. entries:

const map = new Map(a); map.set("one".1);
map.set("two".2);

const obj = Object.fromEntries(map);

console.log(obj.one); / / 1
Copy the code

Map vs WeakMap

WeakMap is similar to Map, with two main differences:

  1. WeakMapAccepts only objects as key names.
const map = new WeakMap(a); map.set(1.2);
// TypeError: Invalid value used as weak map key

map.set({}, 1);
Copy the code
  1. WeakMapThe object to which the key name refers is not counted in the garbage collection mechanism.
let obj = { name: "Matt" }; // object can be accessed

let map = new Map(a); map.set(obj,true);

obj = null; // Although the object has been overwritten, the old object can still be accessed in the map
Copy the code

How does WeakMap deal with this situation:

let obj = { name: "Matt" };

let weakMap = new WeakMap(a); weakMap.set(obj,true);

obj = null; // Overwrite the object, which will also be deleted in weakMap
// weakMap is now empty
Copy the code

WeakMap has only four methods: Get, set, Delete, and HAS. The reason why there is no such attribute or method as size is because of this mechanism, the length of WeakMap instance may change at any time, so it is forbidden to access WeakMap’s size attribute from the rule, and naturally it will not provide the several attributes used for traversal.

conclusion

This article introduces the features of objects and maps from some similarities and differences, hoping to help you understand their advantages and disadvantages, and then choose the right data structure in the right scenario.

Pay attention to our