directory

  1. Map
  2. Set
  3. WeakMap
  4. WeakSet
  5. reference
  6. conclusion

A Map

set get hasCommonly used API

JavaScript objects are essentially collections of key-value pairs (Hash structures), but traditionally strings can only be used as keys. This puts a great limit on its use

To solve this problem, 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.

A Map is a structure of key-value pairs with extremely fast lookup times

const m = new Map(a);const o = {p: 'Hello World'};

m.set(o, 'content')
m.get(o) // "content"

m.has(o) // true
m.delete(o) // true
m.has(o) // false
Copy the code

The above code uses the set method of the Map structure to treat the object O as a key of M, then reads the key using the get method, and then deletes the key using the DELETE method.

The example above shows how to add members to a Map. As a constructor, a Map can also take an array as an argument. The members of this array are arrays representing key-value pairs.

const map1 = new Map([['name'.'Joe'],
  ['title'.'Author']]); map1.size/ / 2
map1.has('name') // true
map1.get('name') // select * from *;
Copy the code

1) Traversal method

The Map structure natively provides three traverser generating functions and one traversal method.

  • Map.prototype.keys(): returns a traverser for key names.
  • Map.prototype.values(): returns a traverser for key values.
  • Map.prototype.entries(): returns a traverser for all members.
  • Map.prototype.forEach(): Traverses all Map members.

Note in particular that the Map traversal order is the insertion order.

2) Map structure into an array

A faster way is to use the extension operator (…) .

Of course, you can convert it to an object, or you can convert it to JSON.

const map = new Map([[1.'one'],
  [2.'two'],
  [3.'three']]); [...map.keys()]/ / [1, 2, 3]

[...map.values()]
// ['one', 'two', 'three']

[...map.entries()]
// [[1,'one'], [2, 'two'], [3, 'three']]

[...map]
// [[1,'one'], [2, 'two'], [3, 'three']]
Copy the code

The second Set

ES6 provides a new data structure, Set. It is similar to an array, but the values of the members are unique and there are no duplicate values.

The Set itself is a constructor used to generate the Set data structure.

0) Operation method and traversal method

Operation method

  • Add (value) : Adds a value and returns the Set structure itself.
  • Delete (value) : deletes a value and returns a Boolean value indicating whether the deletion is successful.
  • Has (value) : Returns a Boolean value indicating whether the value is a member of Set.
  • Clear () : Clears all members with no return value.

Traversal methods

  • Keys () : returns a traverser for key names
  • Values () : Iterator that returns key values
  • Entries () : Returns a traverser for key and value pairs
  • ForEach () : Iterates through each member using the callback function

1) Usage scenarios

1.1) Array to heavy

// Remove duplicate members of the array
[...new Set(array)]
let arr = [3.5.2.2.5.5];
let unique = [...new Set(arr)];
/ / [3, 5, 2]
Copy the code

1.2) Removes duplicate characters from a string

[...new Set('ababbc')].join(' ')
// "abc"
Copy the code

1.3) ** It is easy to implement Union, intersection, and Difference using Set.

天安门事件

let a = new Set([1.2.3]);
let b = new Set([4.3.2]);

/ / and set
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}

/ / intersection
let intersect = new Set([...a].filter(x= > b.has(x)));
// set {2, 3}

// The difference between a and b
let difference = new Set([...a].filter(x= >! b.has(x)));// Set {1}
Copy the code

Three WeakMap

let k1 ={a:1}; let k2 ={b:2}; let v1 =[1.2]; let v2=[3.6]
let wm = new WeakMap([[k1, v1], [k2, v2]]) 
/ / WeakMap {{... } = > Array (2), {... } => Array(2)}
Copy the code

WeakMap has very few methods, only four [add, delete, change and check] : delete, GET, HAS and set.

Note: WeakMap has restrictions on Key, it must be Object (Symbol does not work either)

1) WeakMap scenario

It can be seen from the following IIFE that WeakMap is recovered outside the IIFE function domain. And the Map is not

var map = new Map(a);var weakmap = new WeakMap(a); (function IIFE(){
    var k1 = {x: 1};
    var k2 = {y: 2};

    map.set(k1, 'k1');
    weakmap.set(k2, 'k2');
})()

map.forEach((val, key) = > console.log(key, val))
// Weakmap. forEach(...) ERROR!
Copy the code

After the IIFE function is run, do we need to save k1 objects in the map?

The answer should be “no save” : k1 and K2 are scoped in IIFE, and then we won’t be able to retrieve these two references, leaving only side effects in the map. But after IIFE, when traversing a map — map.foreach (…) We can still find {x: 1}, and we can’t even delete the object except by calling the clear method; Garbage collection doesn’t work with {x: 1}, and over time, memory runs out.

Four WeakSet

WeakSet structure is similar to Set, which is also a collection of non-repeating values, with only three methods and no attributes

  • Weakset.prototype. add(value) : Adds a new member to the WeakSet instance.
  • Weakset.prototype. delete(value) : Clears the specified member of a WeakSet instance.
  • Weakset.prototype. has(value) : Returns a Boolean value indicating whether a value is in a WeakSet instance.

WeakSet members can only be objects, not other types of values

let weak = new WeakSet(); weak.add(1); //Uncaught TypeError: Invalid value used in weakSetCopy the code

1) the role

Weak, as its name indicates, is a weak reference to an object, which is not considered by the garbage collection mechanism, so it does not leak memory, and is not traversal, because you do not know when the object reference disappears, and there is no size attribute, so you do not know the length

let weak = new WeakSet(a); weak.add({}); weak.add([]);var timeId = setInterval(() = > {
    console.log(weak);
}, 1000);
Copy the code

reference

  • WeakMap
  • WeakMap
  • Set

conclusion

  • The Object structure providesString valueThe corresponding,The Map structure provides value - value correspondence.Is a more sophisticated implementation of Hash structures
  • JavaScript objects are essentiallyA collection of key-value pairs (Hash structure), but traditionally you can only use strings as keys. This puts a great limit on its use
  • JS memory ManagementThis is useful in memory-sensitive scenarios. Although a high-level language like JS hides a lot of memory management functionality, it doesn’t solve some extreme cases anyway.It is still up to the developer to take care of some of the memory details. ECMAScript is proposedWeakMap(There’s one moreWeakSet), finally giving developers a wayProactive solutions to memory reclamation.
  • WeakMap method is also very few, onlyFour [add, delete, change, check]:delete,get,has,set.