The difference between Set, Map, WeakSet and WeakMap

1. Set
is similar to an array, but the values ​​of the members are unique and there are no duplicate values.

Set itself is a constructor, used to generate Set data structure.

Array deduplication and string deduplication:

[...new Set(array)];

 Array.from(new Set(array));
 
[...new Set('ababbc')].join('')
// "abc"

When adding a value to the Set, no type conversion occurs.

The Array.from method can convert the Set structure into an array.

const items = new Set([1, 2, 3, 4, 5]);
const array = Array.from(items);

! ! ! Use Set to easily implement Union, Intersect and Difference.

let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);

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

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

// (a 相对于 b 的)差集
let difference = new Set([...a].filter(x => !b.has(x)));
// Set {1}

2. The WeakSet
structure is similar to Set, and it is also a collection of unique values. However, there are two differences between it and Set.
First of all, the members of WeakSet can only be objects, not other types of values.
The members are weak references, can be recycled by garbage collection mechanism, can be used to save DOM nodes, not easy to cause memory leaks,
can not be traversed, methods include add, delete, has

3. Map
is essentially a collection of key-value pairs. Similar to a collection, it
can be traversed, and it can be converted with various data formats in many ways.

Four, WeakMap
only accepts objects as keys (except null), and does not accept other types of values ​​as keys.
Keys are weak references. The key value can be arbitrary. The object pointed to by the key name can be garbage collected. At this time, the key name Is invalid and
cannot be traversed, the methods are get, set, has, delete

Guess you like

Origin blog.csdn.net/Beth__hui/article/details/109367917