preface

Map, WeakMap, Set, WeakSet, as the new reference data types of ES6, the most commonly used is nothing more than the use of Set to remove weight, but the usage and application scenarios of Map, WeakMap and WeakSet are very vague. Here, through the integration of the Little Red Book and MDN documents, we can learn from: simple usage, use scenario, difference. Record the use and differences of these four reference types.

Map

Map: A new feature in ES6, which is a new collection type, a “key/value” stored object.

Initialization: You can assign values at creation time or add key-value pairs via its built-in API: set() method. Example: Initialize assignment.

const m1 = new Map([['key1'.'value1'],
    ['key2'.'value2']])Copy the code

Map provides a number of simple examples :(add, delete and query)

Add: set ()

Set () : assignment.

It returns an instance of the map, so you can do chain operations

m1.set(['key3'.'value3']).set(['key6'.'value6'])
Copy the code

Delete: delete (), the clear ()

delete()

Removes key-value pairs for corresponding keys. All key-value pairs with the same key-value are deleted.

m1.delete(key)
Copy the code

clear()

Removes all elements from the Map object

m1.clear() 
Copy the code

Check: the get (), from the ()

get()

Returns the value of the corresponding key in the Map object

m1.get(key)
Copy the code

has()

Returns whether the Map object has a corresponding key Boolean value

For example:

const m2 = new Map([[]])
m2.has(undefined) //true
m2.get(undefined) //undefined
Copy the code

Get quantity: size()

Gets the number of key-value pairs

m1.size()
Copy the code

Order and iteration: Entries ()

Map maintains the insertion order of key-value pairs, so you can iterate based on the insertion order. Map provides entries() to reference symbol.iterator.

There is a picture and there is a truth:

Iterators cannot be used because Object has no Symbol. Iterator. For of and for in

Iterating keys: keys(), values()

keys()

MDN: Returns a referenced Iterator. It contains the keys that are inserted sequentially for each element in the Map object.

values()

MDN: Returns a new Iterator. It contains values that are inserted sequentially for each element in the Map object.

Keys () and values() refer to the iterator, whose return contains the value and done attributes. Note here that keys and values are both values obtained by next()

WeakMap (WeakMap)

Es6 is a new feature and a new collection type. Is a “sibling” type of Map whose API is also a subset of Map.

As defined in the Little Red Book: week-> ‘weak hold’, this means that these keys are not officially referenced and will not be garbage collected. I think that just as with closures, reference values are used, so as long as the key exists, it exists in the map and is not garbage collected. For example:

const wm = new WeekMap();
wm.set({}, 'val');Copy the code

The above code initializes an empty object with a key through set(). Since there is no reference to the empty object, this is treated as garbage collection.

The following example makes it clear that “not being officially held does not prevent garbage collection”

const wm = new WeakMap(a);const container = {
    key: {}
}
wm.set(container.key, 'val');
function removeReference() {
    container.key = null;
}
Copy the code

This is initialized by a key that refers to the empty object, which is a reference (the key that points to the Container) so it is not garbage collected. Instead, you can call removeReference to clean up the reference values and finally achieve the effect of garbage collection. (One solution to closures is to set the reference value to NULL.)

Methods provided:

As you can see from the WeakMap instance object, there are no iterable methods provided. Because of ‘weak’, there is no official citation.

See MDN for more details on how to use the other methods

Set

ES6 Added a collection type. Elements in a Set occur only once, that is, the elements in a Set are unique

Increase the add ()

Adds an element to the end of the Set. Returns the Set object. Returns an instance of a collection, so you can do this by implementing a chain operation (the same goes for Map’s set())

const s = new Set()
s.add('val1').add('val2').add('val3')
Copy the code

Delete the delete (), the clear ()

delete()

Delete current value returns a Boolean value

s.delete(value)
Copy the code

clear()

Clears all elements in the Set object

s.clear()
Copy the code

Check from the ()

Query whether there is a current value returns a Boolean value

s.has(value)
Copy the code

WeakSet(WeakSet)

WeakSet and Set are introduced in the same way as WeakMap and Map, which have been described in detail above.

Refer to MDN for its usage

Use scenarios of WeakMap

1. Private variables

In my previous article, I also talked about JS encapsulation, inheritance, polymorphism. It’s a similar idea.

Code from the Little Red Book:

const User = (() = > {
    const wm = new WeakMap(a);class User {
        constructor(id) {
            this.idProperty = Symbol('id');
            this.setId(id);
        }
        setPrivate(property, value) {
            const privateMembers = wm.get(this) | | {}; privateMembers[property] = value; wm.set(this, privateMembers)
        }
        getProvate(property) {
            return wm.get(this)[property]
        }
        setId(id) {
            this.setPrivate(this.idProperty, id)
        }
        getId(id) {
            return this.getProvate(this.idProperty)
        }
    }
    return User
})()
const user = new User(123)
console.log(user.getId()) / / 123
user.setId(456)
console.log(user.getId()) / / 456
Copy the code

Implementation: use the object instance as the key and the dictionary of the private member as the value. In the above way: The key name of the weak mapping cannot be obtained, so the corresponding value cannot be obtained. The main use of the Symbol object.

2. DOM node metadata

WeakMap instances do not prevent garbage collection. If we want to associate styles with a DOM node, we set the DOM node to the key name. When the node is removed (reference address is null), garbage collection is used to free memory.

Set usage scenarios

1. Es6 extension operator with new Set()

var arr = [1.2.3.2.1];
var result = [...new Set(arr)]
console.log(result) / / [1, 2, 3]
Copy the code

Array.from with new Set()

The array.from () method creates a new, shallow-copy Array instance from an array-like or iterable.

var arr = [1.2.3.2.1];
var result = Array.from(new Set(arr))
console.log(result) / / [1, 2, 3]
Copy the code

The difference between Map and Object

  1. The Map to reflectKey/value pairFormal data structures (MapCan supportAny JS data typeAs the key name, andObjectCan only beThe numerical,stringorsymbol)
  2. Memory footprintMap stores about 50% more key-value pairs than Object
  3. Insert performance: Insert speed does not increase linearly with the number of key-value pairs, but Map performance is better for large numbers of inserts.
  4. To find the speedObject is faster with a small number of key-value pairs
  5. Delete the performance: Map is quickly deleted in most browser engines.

conclusion

  1. Es6 New reference data types: Map, WeakMap, Set, and WeakSet
  2. The Map, WeakMap:Key/value pairmapping
  3. The Set, WeakSet:valueA collection of
  4. withweakWeak reference to,Don't stopGarbage collection mechanism,An iterative
  5. WeakMap and WeakSet can be used as the storage type when the DOM node is modified.

Previous JS articles:

The interview questions

Depth copy method summary, practice

Learn about JS modularity, IFEE in a few minutes

JavaScript implements encapsulation, inheritance, and polymorphism