preface

This is the first in a series of headlines. I don’t care, I answer, my autumn recruit will ask!!

Hope to help you too ~~

The body of the

WeakMap

What is it?

Like a map, it is used to generate a collection of key-value pairs

The difference between map and MAP?

2. The difference in use:

  • Weakmap only accepts objects as key names (excluding NULL)
  • The object to which the key name of a WeakMap points is not included in the garbage collection mechanism (this is the same as for a Weakset, which is that the garbage collection mechanism is not affected by this reference).

Note: The weak reference is to the key name, and the key value is normally referenced

Differences in API:

  • There is no traversal operation (as with Weakset), so there are no keys, values, and entries traversal methods

Only get, set, HAS, and DELETE methods are available

Why did you design this thing?

* Problem :* When we want to store some data on an object, this causes us to reference the object. Here’s an example:

Const arr = [[e1, 'foo element '], [e2, 'bar element '],];Copy the code

However, when the object is no longer needed in other logic and needs to be deleted, we need to manually delete the reference. Otherwise, the garbage collection mechanism will not release the memory occupied by the object, resulting in a memory leak.

Weakmap is designed to solve this problem. The reference to its key name is weak and is not considered by the garbage collection mechanism.

Usage scenarios

When you want to add data to an object, but don’t want to interfere with the garbage collection mechanism, you can use weakMap classic usage scenarios:

  • Weakmap can be used to add data to the DOM element of a web page. When DOM is cleared, the key name saved by WeakMap will also disappear
  • Deploy private properties:
const _counter = new weakMap()
const _action = new WeakMap()
class Countdown{
    constructor(counter,action){
        _counter.set(this,counter)
        _action.set(this,action)
    }
}
Copy the code

In the above code, the property is initialized in the constructor and is a weak reference to the instance this. Benefit: If you delete the instance, they disappear with it, without causing a memory leak

Map

The characteristics of

  • Any data structure with an Iterator interface where each member is a two-element array can be used as an argument to the Map constructor. The first element is the key. The second element does value
  • The rule for determining whether the attribute is the same as the Set is consistent:
    1. Always think of reference data types as two different keys or values.
    2. For normal data types, congruent is treated as identical

Instance properties and action methods

  • Size attribute: returns the total number of members in the Map structure
  • Set (key,value) : Sets the value corresponding to key to value. Then return the entire map structure. If the key already has a value, the key value is updated. You could write it in a chain
  • Get (key) : reads the key value corresponding to the key and returns it. If not, return undefined
  • Has (key) : determines whether the key is in the current Map object
  • Delete (key) : deletes a key. Return true on success, false otherwise
  • Clear () : clear all members, no return value

Traversal method – same as Set

Map and other data structures

  • Map to object: copy the Map once. If there is a non-string key name, the Map is automatically converted to a string
  • Object to Map: object.Entries (obj)(traversing all entries in [key, value] form)
  • The Map to JSON:
    1. Map key names are strings, converted to object JSON
let obj = {"a":1, "b":2};
let map = new Map(Object.entries(obj));
Copy the code

WeakSet

  • Like a Set, it is a Set of non-repeating values

The difference between Set and Set:

  • The members of a WeakSet can only be objects and cannot be values of other types.

  • WeakSet does not have a size attribute and cannot iterate over its members. Because members are weak references and can disappear at any time, the traversal mechanism cannot guarantee the existence of members, and it is likely that the members will not be retrieved right after the traversal ends. One use of WeakSet is to store DOM nodes without worrying about memory leaks when they are removed from the document.

  • Second, the objects in a WeakSet are all weak references, that is to say, the garbage collection mechanism will not consider whether the object still exists in a WeakSet.

Cause: Because garbage collection relies on reference counting, if a value is not referenced zero times, the immediate collection mechanism will not free the memory. When you end up using the value, you sometimes forget to dereferencing it, resulting in memory not being freed and potentially causing a memory leak. WeakSet does not have this problem. Usage scenario: Therefore, WeakSet is suitable for holding a group of objects and holding information bound to objects. As long as the object disappears externally, its reference in the WeakSet will automatically disappear. Pay attention to

  • A member of a WeakSet is not suitable for reference because it can disappear at any time.
  • Since the number of members inside a WeakSet depends on whether the garbage collection mechanism is running, the number of members before and after the operation is likely to be different, and when the garbage collection mechanism is running is unpredictable, so ES6 stipulates that a WeakSet cannot be traversal.

grammar

  • WeakSet can accept any object with an Iterable interface as a parameter. If the members of the received parameters are reference data types, then they automatically become members of the WeakSet instance object
  • The method of WeakSet
    1. Add (value) : Adds a new member to the instance
    2. Delete (value) : Clears the specified member of the instance
    3. Has (value) : Returns a Boolean value indicating whether the value is in the instance

Set

  • What is? ES6 provides a new data structure, similar to an array, where the values of members are unique and there are no duplicate values.
  • How does it work?
  1. Set is a constructor that generates a Set data structure
  2. You can add members to the Set structure through the add() method without adding duplicate values
  3. The Set function can take an array (or some other data structure with an iterable interface (that is, a data type that can be traversed) as an argument for initialization

Note:

  • No cast occurs when a value is added to a Set. soadd(5)andadd('5')It’s different
  • The Set internally determines whether two values are the same, and has its own algorithm rules, similar to (===), where both types and data are equal, but there are special cases:
  • NaN is considered to be equal to itself within the Set. That is:add(NaN)And then, againadd(NaN)Considered repetitive, a set will end up with only one NaN
  • In a Set, two objects are always not equal. namelyadd({})Again,add({})Set. The size of 2

Why {} === {} is false Reference data types compare references, not values. False for two different objects with obviously different reference addresses

Methods and properties of the Set instance

  • attribute
    1. Set. The prototype. The constructor constructor = Set
    2. Set.prototype.size Returns the total number of members of the Set instance
  • methods
    • Operation method
    1. Add (value) Adds the default value and returns the Set structure itself
    2. Delete (value) Deletes a value. A Boolean value is returned to indicate whether the value is successfully deleted
    3. Has (value) Returns a Boolean value indicating whether the value is a member of the Set
    4. Clear () : clear all members, no return value
    • Traversal methods

    Note: The Set traversal order is the insert order.

    1. keys()
    2. values()
    3. Entries () : The returned iterator, containing both key names and values, printed as an array with identical members

Note: The first three methods return an iterator object. Since the Set has no key name, only a key value, keys and values behave exactly the same. The first argument: the callback function. The parameters of the callback are the key value, the key name, and the collection itself. The second argument: binds the this object inside the handler

  • Note:
  1. Because instances of Set are traversed by default, this means you can ignore the values method and just use for… The of loop iterates through the Set
  2. 1, array. from can convert a set structure into an Array. So array. from(new Set(Array)) is a way to de-duplicate an Array. […new Set(arr)]
  • Important applications of Set
    1. It is easy to implement the union, intersection, difference set
    Let a = newSet ([1, 2, 3]); Let b = newSet (31 [4]); // let union=**newSet([...a,...b]); * * / / Set {1, 2, 3, 4} intersection / / * * * * let intersects = * * newSet ([...] a filter (x = > b.h as (x))); * * / / set {2, 3} / / (a relative to b) difference set * * * * let difference = * * newSet ([...] a filter (x = >! b.has(x))); ** // Set {1}Copy the code
  1. If you want to synchronously modify the original Set structure during the traversal operation, there is no direct method, but there are two indirect methods:
Let Set =newSet([1,2,3]); // let Set =newSet([1,2,3]); set=newSet([...set].map(val => val *2)); Let set=newSet([1,2,3]); let set=newSet([1,2,3]); set=newSet(**Array.from(set, val => val *2)**); // The set value is 2, 4, 6Copy the code

In addition: Array. The from

  • parameter
    1. A pseudo-array object or iterable that you want to convert to an array (set, map, string, array is fine)
    2. Callback function. This callback is performed for each element in the new array
    3. The this object when the callback function executes above
  • Return the value of a new array instance

conclusion

This section describes the differences between Set, Map, WeakSet, and WeakMap.

  • Set and WeakSet and Map and weakMap:
  1. A member of a Set can be any data structure, while a member of a WeakSet can only be an object
  2. References to objects in a Set are normal references, while a Weakset is a weak reference, which does not affect the garbage collection mechanism
  3. Weakset cannot iterate over its members. Weakset does not have the size property and the three traversal methods of keys, values and entries
  • The set and map:
  1. A set instance is a collection of distinct values with the same key name and value
  2. A map instance is a collection of key-value pairs. Any data structure can be used as an object with a key name

conclusion

Prepare for autumn recruit, this is the first article in the series of recovery stage. Welcome to continue to pay attention to like, rushed together!!