Introduction to the

Set and Map are new data structures in ES6. But the values of the members are unique, and there are no duplicate values.

  • A Set is like an array, with unique member values.

  • WeakSet is similar to Set, but its members can only be objects, and there is no traversal operation. It is automatically reclaimed if it is not referenced.

  • A Map is similar to an object. The key value is not limited to strings, but the member value is unique.

  • WeakMap is similar to Map, but only accepts the object as the key name (except null) and does not iterate. It is automatically reclaimed if it is not referenced.

Set

A Set is similar to an array, but the values of its members are unique and have no duplicate values.

create

var s = new Set(a); s.add('haha');
s.size; / / 1

typeof s;                          // "object"
s instanceof Object;               // true
Object.prototype.toString.call(s); // "[object Set]"
Copy the code

attribute

  • Set.prototype.constructorThe: constructor is Set by default.
  • Set.prototype.size: Returns the total number of members of the Set instance.

methods

Set.prototype.add(value).

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 was 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 method:

  • keys(): returns a traverser for key names
  • values(): returns a traverser for key values
  • entries(): returns a traverser for key-value pairs (with the same key name and value)
  • forEach(): Iterates through each member using the callback function, but returns no value

Convert to an array

The array. from method converts a Set structure to an Array.

const items = new Set([1.2.3.4.5]);
const array = Array.from(items);
Copy the code

Usage scenarios

1. Array deduplication

The Set structure can accept an array as an input parameter, which provides a way to de-duplicate the array

function dedupe(array) {
  return Array.from(new Set(array));
}

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

You can also use… Implementation to heavy

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

2. Pick up and set

let a = new Set([1.2.3]);
let b = new Set([4.3.2]);
/ / and set
let union = new Set([...a, ...b]);
Copy the code

3. Take the intersection

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

4. Take the difference set

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

WeakSet

Difference from Set

WeakSet structure is similar to Set, which is also a collection of non-repeating values. However, it differs from Set in several ways:

  1. WeakSet members can only be objects, not other types of values
  2. WeakSet objects are weak references, if other objects no longer reference the object, then garbage collection mechanism will automatically recover the memory occupied by the object, not considering the object still exists in WeakSet
  3. WeakSet has no size attribute and cannot use traversal operation

create

const a = [[1.2], [3.4]].const ws = new WeakSet(a);
// WeakSet {[1, 2], [3, 4]}

Object.prototype.toString.call(ws) // "[object WeakMap]"
Copy the code

Available methods

Add (), delete(), has()

Usage scenarios

1. Avoid memory leaks

Because WeakSet is automatically reclaimed when it is no longer in use, it can be used to store DOM nodes without worrying about memory leaks when they are removed from documents.

const foos = new WeakSet(a)class Foo {
  constructor() {
    foos.add(this)
  }
  method () {
    if(! foos.has(this)) {
      throw new TypeError('foo.prototype. method can only be called on instances of Foo! '); }}}Copy the code

The above code ensures that instance methods of Foo can only be called on instances of Foo. The advantage of using WeakSet here is that the reference to the instance by foos is not counted in the memory reclamation mechanism, so when deleting the instance, you do not need to consider foos and there is no memory leak.

Map

Map Data structure. 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.

create

const map = new Map([['name'.'Joe'],
  ['title'.'Author']]); map.size/ / 2
map.get('name') // "/"
map.get('title') // "Author"

typeof map;                          // "object"
map instanceof Object;               // true
Object.prototype.toString.call(map); // "[object Map]"
Copy the code

attribute

  • Map.prototype.size: Indicates the total number of Map structure members

methods

Map methods are all inherited from the prototype, map.prototype. set(key, value).

Operation method:

  • set(key, value): Sets the key name and returns the entire Map structure
  • get(key): Reads the key corresponding to the key. If the key cannot be found, undefined is returned
  • has(key): Indicates whether a key is in the current Map object
  • delete(key): Deletes a key successfully, returns true, otherwise returns false
  • clear(): Clears all members with no return value

Traversal method:

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

Convert to an array

Using extension operators (…) , you can convert the Map structure into an array structure

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

In addition to converting to arrays, it can also convert to and from other data structures, such as

  • The Map becomes an object, and the object becomes a Map
  • Map is converted to JSON, and JSON is converted to Map

Usage scenarios

  1. The key value is not necessarily a string
  2. When you need to find data in a two-dimensional array
  3. When you need to convert a two-dimensional array

WeakMap

Differences with Map

Differences between WeakMap and Map:

  1. WeakMap only accepts objects as key names (except null) and does not accept values of other types as key names
  2. The object to which the key name of WeakMap points is not included in the garbage collection mechanism
  3. WeakMap has no traversal operation

create

const wm = new WeakMap(a);const key = {foo: 1};
wm.set(key, 2);
Copy the code

Available methods

Get (), set(), has(), delete()

Usage scenarios

1. Avoid memory leaks

This is often used with Dom nodes as key names. Once the DOM node is removed, the state disappears automatically, with no risk of memory leaks.

let myWeakmap = new WeakMap(a); myWeakmap.set(document.getElementById('logo'),
  {timesClicked: 0});document.getElementById('logo').addEventListener('click'.function() {
  let logoData = myWeakmap.get(document.getElementById('logo'));
  logoData.timesClicked++;
}, false);
Copy the code

2. Deploy private properties

As private properties, if instances are deleted, they disappear without causing a memory leak.

const _counter = new WeakMap(a);const _action = new WeakMap(a);class Countdown {
  constructor(counter, action) {
    _counter.set(this, counter);
    _action.set(this, action);
  }
  dec() {
    let counter = _counter.get(this);
    if (counter < 1) return;
    counter--;
    _counter.set(this, counter);
    if (counter === 0) {
      _action.get(this) (); }}}const c = new Countdown(2.() = > console.log('DONE'));

c.dec()
c.dec()
// DONE
Copy the code