One, the Map

Maps can be used to store key-value pairs, extending the contents of Object to some extent.

1. Basic API of Map

Create a new Map instance

// Create an empty map
let map = new Map(a)// Pass in an iterable containing a group of key-value pairs,
// Incoming iterables are inserted into the new map instance in sequence
let arr = [
    ['key1'.'val1'],
    ['key2'.'val2'],
    ['key3'.'val3']]let map1 = new Map(arr) 
// Can also be a custom iteration object
Copy the code
  • set(key, value)Add new key-value pairs and return one mapping instance at a time (so it can be chained)
  • get(key)Returns the corresponding key value based on the key name
  • sizeProperty that returns the number of key-value pairs currently stored
  • has(key), returns whether the currently passed key name exists, and returns a Boolean type
  • delete(key)To delete the specified key-value pair
  • clear()Clear the mapping and delete all key-value pairs
let m = new Map(a)// Add a new key-value pair
m.set('name'.'zhangsan')
 .set('age'.20)

// Get the corresponding key
console.log(m.get(name));

// Determine if the key name is on the instance
console.log(m.has('name'));

// Determine the number of stored key-value pairs

console.log(m.size);

// Delete the specified key-value pair
m.delete('name')

// Clear the mapping and delete all key-value pairs
m.clear()
Copy the code

Some iterative methods of Map

When inserting content, the Map instance maintains the insertion order, and the order traversed is the insertion order, while the object traversal order may not be the insertion order. So the following three methods work exactly as in Object, except that the map calls iterate over the order in which the key-value pairs are inserted

  • Entries are the same as the iterated map itself, which is also iterable
  • keys
  • values

Methods that are different from objects

  • ForEach is different from array forEach. The map forEach callback takes a value and a key, and the second parameter is the value of this, the same as the array callback
let m = new Map([['key1'.'value1'],
  ['key2'.'value2'],
  ['key3'.'value3']
])

m.forEach((value, key) = > {
  console.log(value, key);
})
// value1 key1
// value2 key2
// value3 key3
Copy the code

What problem does Map solve with Object

Object can only use number, string, and Symbol as key names. Map can use any type as build names. The same thing between the two is that there are no restrictions on key values. Object can be converted by toString when using other types as key values. So when you need to store more types, use Map

Select Object and Map

  1. memory

A map can store more memory than an Object for the same size. When inserting, the two methods are similar. When inserting a large amount of data, map 3 is still selected. The difference in search speed is very small, and when using consecutive integers as attributes, the call browser can be optimized, and the speed may be higher than 4. Delete Performance When you delete a map, the map is better

Set

Basic API

Create a new Set instance

// Create an empty collection
let s = new Set(a)// Pass in an iterable that contains the new elements to be inserted into the collection
let s = new Set([1.2.3])
Copy the code
  • add(item)Add a new element, like map’s set method, which returns a new instance, so it can be called chained
  • has(item)Queries for specified elements
  • sizeProperty to view the number of elements in the collection
  • delete(item)Deletes the specified element and returns a Boolean value indicating whether the element to be deleted exists
  • clear()Clear collection, remove all elements

The iteration

Set also maintains the order of insertion, iterating in the insertion order

  • keys()
  • values()
  • Self iterable

The result of all three operations is the same, each iterating out each element

for(let i of s.values()) {
  console.log(i);
}
for(let i of s.keys()) {
  console.log(i);
}
for(let i of s) {
  console.log(i);
}

Copy the code
  • “Entries, an array containing duplicate elements of two collections
let s = new Set([1.2.3])

for(let i of s.entries()) {
  console.log(i);
}

/ / [1, 1)
/ / (2, 2)
/ / [3, 3]
Copy the code

Understanding of weakMap

WeakMap, as can be seen from its name, is a weakMap mapping relationship, that is, WeakMaps keeps a weak reference to the object referenced by the key name. Weak references are the references that can be reclaimed by the garbage collection mechanism at any time. Objects declared directly are as follows

let o = {} // Creating an object like this is a strong reference. Strong references are not garbage collected
// Only if null is set will it be collected
o = null // Can be garbage collected
Copy the code

When an object is declared and the Map refers to the object as the key name

let o = {name: 'zhangsan'}

let m = new Map(a)// Map strongly references o as the key
m.set(o, 1) 

// When o= null, only references to the object are removed
// But m still refers to the object, so it cannot be cleared

Delete (key = null); // Delete (key = null
Copy the code

Therefore, the role of weakMap is shown. Because its key-value pair is a weak reference, if so, when the object key= NULL, because its original key value is a weak reference, the reference object will be collected when the next garbage collection is executed. Therefore, the function of WeakMap is to retain the weak reference to the object referenced by the key name, that is, if the object referenced by the key name is not referenced by other variables, garbage collection will release the memory occupied by the object, because the weak reference may be cleared by garbage collection at any time, and the implementation of garbage collection mechanism is actually unpredictable. So WeakMap can not traverse, simple examples to illustrate

  • When weakMap key value is not referenced
let wm = new WeakMap(a)// The empty object is not referenced by any value, just as a key
// As a result, the key/value pairs are destroyed and the value itself is garbage collected
wm.set({}, 1)
console.log( wm.get({})) // undefined
Copy the code
  • When a value is referenced
let wm = new WeakMap(a)// Create an object that references key
let obj = {
  key: {}}// Use key as the key in the instance
wm.set(obj.key, 1)

// The key-value pair can be accessed
console.log(wm.get(obj.key));  / / 1

// When obj's reference to key is removed, there is no corresponding key-value mapping in WM
obj.key = null
console.log(wm.get(obj.key)); // undefined
Copy the code
  • The four methods of WeakMap,
  • get()
  • set()
  • has()
  • delete()

Weak can only be objects

Application scenarios of WeakMap

1. Data caching

WeakMap can be used when we need to store some properties without modifying the original object or store some calculated values based on the object without having to worry about whether the values are reclaimed

// For example, cache the length of object attributes
const cache = new WeakMap(a)function keyLength(obj) {
  // If this data is present in the cache, it is returned directly
  if(cache.has(obj)) {
    return cache.get(obj)
  } else {
    // If not, the current object's key length is stored in the cache
    const count = Object.keys(obj).length
    cache.set(obj, count)
    // Return the length of this calculation
    return count
  }
}
Copy the code

2. Data in the DOM

Sometimes the dom node associated may be some data, such as whether to disable, can use the map to make them, but if there is some action may need to delete the dom node, this time, if use normal map dom node while deleted, but he still was quoted in the map, so the cost of memory, at this time, WeakMap can be used to achieve this, as follows.

let wm = new WeakMap(a)const btn = document.querySelector('#btn')

// Add some associated data to the BTN node
m.set(btn, {disabled:true})
Copy the code

reference

  • ES6 series value WeakMap
  • JavaScript Advanced Programming