If the profile

Set in ES6, juejin.cn/post/701244… , this time I wrote the basic syntax of Map and WeakMap in ES6, which may not be very complete. If there is wrong or inaccurate place, welcome everyone to put forward 😄, I also actively modify. Below begins the body:

The basic grammar

ES6 provides Map data structures. It is a collection of key-value pairs similar to objects, but the range of “keys” is not limited to strings. Values of all types (including objects) can be used as keys. In other words, the Object structure provides string-value mapping, and the Map structure provides value-value mapping, which is a more complete Hash structure implementation. If you need key-value data structures, Map is better than Object.

let m = new Map([iterable])
Copy the code

Iterable can be an array or other Iterable object whose elements are key-value pairs. Each key-value pair is added to the new Map. Null will be treated as undefined.

Add data

Let m = new Map() let obj = {name: 'xs'} m.et (obj, 'es') console.log(m) } => 'es'} [[Entries]] 0: {Object => "es"} key: {name: 'xs'} value: "es" size: 1 [[Prototype]]: MapCopy the code

Delete the data

Let m = new Map () Margaret spellings et (' name ', 'xs). The set (' age, 18) / / or let m = new Map ([[' name', 'xs'], [18] 'age']) / / delete the specified data M. elete (' name '). The console log (m) / / Map (1) 18} {' age '= > / / delete all the data Map. The clear () / / Map (0) {size: 0}Copy the code

statistics

Let m = new Map([['name','xs'],['age',18]]) // Count the total number of key-values console.log(m.size) //2 // Check whether there are key-values console.log(m.has('name')) // trueCopy the code

Query data

The get() method returns a specified element in a Map object

let m = new Map()
let obj = {
  name: 'xs'
}
m.set(obj,'es')
console.log(m.get(obj)) // es
Copy the code

traverse

  • The forEach() method will perform the callbacks provided in the parameters once forEach key-value pair in the Map object, in insertion order
  • Keys () returns a new Iterator object. It contains the keys that are inserted sequentially for each element in the Map object
  • The values() method returns a new Iterator. It contains values that are inserted sequentially for each element in the Map object
  • The entries() method returns a new Iterator containing [key, value] pairs, iterated in the same order as the Map objects were inserted
  • for… Of traverses each member directly
let map = new Map([ ['name', 'xs'], ['age', 18] ]) map.forEach((value, key) => console.log(value, key)) // xs name 18 'age' for (let key of map.keys()) { console.log(key) // name age } for (let value of map.values()) {  console.log(value) // xs 18 } for (let [key, value] of map.entries()) { console.log(key, value) // name xs age 18 } for (let [key, value] of map) { console.log(key, value) // name xs age 18 }Copy the code

In fact, Object is also stored and read by key value pairs, so what is the difference between Object and Map?

  1. The type of the key

    The keys of an Object can only be strings or Symbols, while the keys of a Map can be any values, including functions, objects, and basic types.

  2. The order of the keys

    Keys in a Map are ordered, while keys added to objects are not. Therefore, when traversing it, the Map object returns key values in the order in which they were inserted.

  3. Key – value pair statistics

    You can directly obtain the number of key-value pairs for a Map using the size attribute, whereas the number of key-value pairs for Object can only be calculated manually.

  4. Traversal of key-value pairs

    A Map iterates directly, whereas an Object iterates by retrieving its key array before iterating.

  5. performance

    Map has some performance advantages in scenarios involving frequent addition and deletion of key-value pairs.

WeakMap

WeakMap structure is similar to Map structure and is also used to generate a set of key-value pairs. However, WeakMap key names only support reference data types, such as: array, object, function.

Let wm = new WeakMap() // WeakMap can use set method to add member wm. Set ([1], 2) console.log(WM) // WeakMap {Array(1) => 2} wm. Set ({name: 'xs'}, 18) console.log(WM) // WeakMap {Array(1) => 2, {... // WeakMap can also accept an array, Constructor const m1 = [1, 2, 3] const m2 = [4, 5, 6] const wm2 = new WeakMap([[M1, 'foo'], [m2, 'bar'] ]) wm2.get(m2) // 'bar'Copy the code

The differences between WeakMap and Map are as follows:

  1. WeakMap only accepts objects (reference data types) as key names (except null) and does not accept values of other types as key names.
const map = new WeakMap()
map.set(1, 2) // Uncaught TypeError: 1 is not an object!
map.set(Symbol(), 2) // Uncaught TypeError: Invalid value used as weak map key
map.set(null, 2) // Uncaught TypeError: Invalid value used as weak map key
Copy the code
  1. The object to which the key name of WeakMap points is not included in the garbage collection mechanism.
Let wm = new WeakMap() wm. Set ({name: 'xs'}, 18) console.log(wm) // WeakMap {{... } => 18} // wm.clear() // Uncaught TypeError: wm.clear is not a function console.log(wm.size) // undefinedCopy the code

As can be seen from the above code, WeakMap does not support the clear() method and has no size attribute, so it does not support traversal.

Therefore, WeakMap, like WeakSet, is a weak reference. This means that if a value of this reference type is collected by the garbage collection mechanism, then the key-value pair corresponding to the instance in it will also disappear automatically.

Note: WeakMap weakly references only the key name, not the key value. Key values are still normal references.

const wm = new WeakMap();
let key = {};
let obj = {foo: 1};

wm.set(key, obj);
obj = null;
wm.get(key)
// Object {foo: 1}
Copy the code

Application scenarios

If there is an H1 tag in the current page, we need to store the tag and remove it automatically when it is not needed, so WeakMap can be used

let wm = new WeakMap()
let elem = document.getElementsByTagName('h1')
wm.set(elem, 'info')
console.log(wm.get(elem)) // 'info'
Copy the code

In the above code, the memory occupied by the object is freed by the garbage collection mechanism if references to the object from other places are removed, which is equal to the number of times the current garbage collection mechanism has been called. The key value pair saved by WeakMap will disappear automatically, so the key value pair stored in WM will be released automatically without occupying memory space and avoiding memory leakage.