1. Set

1.1 Basic Usage

A Set is like an array, but the values of its members are unique. There are no duplicate values. The Set itself is a constructor used to generate the Set data structure.

const s = new Set(); [2,3,4,5,6,4,2,2,7].foreach (x => s.dd (x)) for (let I of s) {console.log(I)} // 2 3 4 5 6 7 // Set does not add duplicate values.Copy the code

The Set function can take an array (or some other data structure with an Iterable interface) as an argument to initialize, as follows:

/ / instance a const set = new set (,2,3,4,5,5 [1]) set [...] / [1, 2, 3, 4, 5] / / two instances of the const items = new set items (,2,3,3,4 [1]). The size 4 / / / / the above code also shows an array to a heavy method [... new Set (array)] / / or string to heavy new Set (' aabbcc) [...]. Join (' ')Copy the code

When adding a value to a Set, no type conversions take place. All values **5 and ‘5’** are different. The algorithm used to determine whether two values are different inside a Set is called ‘same-value-zero equality’. This is similar to ‘===’ except that ‘===’ assumes NaN is equal to itself while ‘===’ assumes NaN is not equal to itself

let set = new Set(); let a = NaN; let b = NaN; set.add(a); set.add(b); Set // set {NaN} // As mentioned above, adding only one NaN to a set illustrates the proof just describedCopy the code

Two objects are always unequal in a Set.

let set = new Set();
set.add({})
set.size // 1

set.add({})
set.size // 2
Copy the code

1.2 Properties and methods of a Set instance

Instances of the Set structure have the following properties

  • Set. The prototype. The constructor / / constructor, the default is Set function
  • Set.prototype.size // Returns the total number of members of the Set instance.

The methods of a Set instance fall into two broad categories: operation methods and traversal methods

Set.prototype.add(value) // Add a value, return the Set structure set.prototype. delete(value) // Delete a value, return a Boolean value, Set.prototype.has(value) // Returns a Boolean value indicating whether the value is a member of set.prototype. clear() // Clears all members, no return value

s.add(1).add(2).add(2); // notice that 2 is added twice s.size // 2 s.haas (1) // true s.haas (2) // true s.haas (3) // false s.delte (2); Const p = {'w': 1, 'h': const p = {'w': 1, 'h': 2 } if(p[a]){ no } // Set const p = new Set() p.add('w') p.add('h') if(p.has(c)){ no }Copy the code

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

Const items = new Set([1,2,3,4,5]) const array = array. from(items) function d(a){return array. from(new Set (a))} d (,2,3,3,5 [1])Copy the code

1.3 Traversal Operations

An instance of a Set structure has four traversal methods for traversing members

  • Set.prototype.keys() // Returns the traversal of the key name
  • Set.prototype.values() // Returns the traversal of key values
  • Set.prototype.entries() // Returns the traversal of key and value pairs
  • Set.prototype.foreach () // use the callback function to iterate over each member

Note: Set traversal order is insertion order, which is useful in certain situations, such as using Set to store a list of callback functions that are guaranteed to be called in the order they were added.

1.3.1 keys(), values, entries()

All three of the above methods return iterator objects. Since the Set structure does not have a key name, only a key value (or the key name and the key value are the same value), the above methods behave exactly the same

let set = new Set(['red', 'green', 'blue']);

for (let item of set.keys()) {
  console.log(item);
}
// red
// green
// blue

for (let item of set.values()) {
  console.log(item);
}
// red
// green
// blue

for (let item of set.entries()) {
  console.log(item);
}
// ["red", "red"]
// ["green", "green"]
// ["blue", "blue"]
Copy the code

Note: An instance of a Set structure is traversable by default. Its default traverser generator is its values method, so we can omit values and use for… Of loops through Set

1.3.2 forEach ()

An instance of a Set structure, like an array, has a forEach method that performs some operation on each member, with no return value. ForEach can use a second argument to represent the this object inside the binding handler.

1.3.3 Application of traversal

Extended operators (…) Internally use for… The of loop sample can be used in the Set structure

let arr = [3, 5, 2, 2, 5, 5]; let unique = [...new Set(arr)]; Let a = new Set([1, 2, 3]); let a = new Set([1, 2, 3]); let b = new Set([4, 3, 2]); // let union = new Set([...a,...b]); / / the Set {1, 2, 3, 4} / / intersection let intersects = new Set ([...] a filter (x = > b.h as (x))); // set {2, 3} // let difference = new set ([...a]. Filter (x =>! b.has(x))); // Set {1}Copy the code

If you want to change the principle Set structure synchronously during traversal, you can only map a new structure from the original Set and then assign to the original Set. The other way is through array. from.

// let set = new set ([1, 2, 3]); set = new Set([...set].map(val => val * 2)); // let set = new set ([1, 2, 3]); set = new Set(Array.from(set, val => val * 2)); // Set values are 2, 4, 6Copy the code

2. WeakSet

WeakSet structure is similar to Set, and it is not a collection of repeated values, but there are two differences with Set. The first one is that its members can only be objects, and the other is that its objects are weak impressions, that is, garbage collection mechanism does not consider WeakSet’s reference to the object. Generally speaking, if the object is not referenced in other objects, Then the object will be reclaimed, regardless of whether the object is in a WeakSet.

Depending on the garbage collection base depends on reference counting, if a value has more than zero references, it will not be collected, but sometimes, after the value is used, it will forget to dereference and memory will not be freed, resulting in a memory leak. However, the reference in WeakSet will not be included in the garbage collection mechanism, so it is suitable for storing temporary objects. Once the outside disappears, the reference in WeakSet will disappear automatically.

Based on the above characteristics, WeakSet members are not suitable for reference, so WeakSet cannot be traversed.

2.1 grammar

It is also a constructor and can be created with new

Const ws = new WeakSet() // As a constructor, WeakSet can accept an array or array-like object as a parameter. All members of the array will automatically become members of the WeakSet instance object.Copy the code

Note: Only the members of the array can be WeakSet members, not the A array itself, which means that the members of the array can only be objects.

2.2 WeakSet method

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

Note: WeakSet also has no size attribute and cannot traverse its members.

3. Map

JavaScript objects, which are essentially collections of key-value pairs, have traditionally been limited to strings as keys. The idea behind maps is that all kinds of values can be used as keys. The Map provides value-value mappings.

Const map = new map ([[' name ', 'zhang'], [' title ', 'the Author]]). Map. The map for the size / / 2. From the (' name ') / / true map. Get (' name ') / / "zhang SAN" map. From the (' title ') / / true map. Get (' title ') / / "Author"Copy the code

Note: Both sets and maps can be used to generate new maps, and if the same key is assigned more than once, the previous one will be overwritten by the later one. In addition, the Map structure only treats references to the same object as the same key. The other two instances of the same will be treated as two keys in the Map.

To sum up, Map keys are actually bound to memory addresses. As long as memory addresses are different, they are treated as two keys. This solves the problem of colliding properties with the same name. If we extend someone else’s library and use the object’s key name, we don’t have to worry about our own property colliding with the original author’s property.

If the Map’s key is a value of a simple type, as long as the two values are strictly equal, the Map will treat them as one key, 0 and -0 are one key, true and ‘true’ are two different keys, undefined and null are two different keys, NaN is also treated as the same key in the Map

3.1 Map Attributes and operation methods

1. The size attribute

The size property returns the total number of Map structure members

const map = new Map()
map.set('foo', ture)
map.set('bar', false)

map.size // 2
Copy the code
2. Map.prototype.set(key, value)

The set method sets the key corresponding to the key name key to value and returns the entire Map structure. If the key already has a value, the key value is updated, otherwise the key is generated.

Const m = new Map() m.et ('e', 6) const m = new Map() m.et ('e', 6) Let Map = new Map().set(1, 'a').set(2, 'b').set(3, 'c').set(2, 'b').set(3, 'c')Copy the code
3. Map.prototype.get(key)

The get method reads the corresponding key and returns undefined if the key is not found

const m = new Map();

m.set('c',  124)
m.get('c')  // 124
Copy the code
4. Map.prototype.has(key)

Returns a Boolean value indicating whether a key is present in the current Map object

let map = new Map()
.set(1, 'a')
.set(2, 'b')
.set(3, 'c')

map.has(1)  // true
map.has(4)  // false
Copy the code
5. Map.prototype.delete(key)

The delete method deletes a key and returns true, or false if the deletion fails

let map = new Map()
    .set(1, 'a')
    .set(2, 'b')
    .set(3, 'c')

map.delete(1)   // true
map.delete(4)   // false
Copy the code
6. Map.prototype.clear()

The clear method clears all members with no return value

let map = new Map()
    .set(1, 'a')
    .set(2, 'b')
    .set(3, 'c')

map.size    // 3
map.clear() 
map.size    // 0
Copy the code

3.2 Traversal method

  1. Map.prototype.keys() : iterator that returns key names
  2. Map.prototype.values(): iterator that returns key values
  3. Map.prototype.entries(): Returns a traverser for all members
  4. Map.prototype.foreach (): Iterates through all members of the Map

Note: The traversal order of a Map is the insertion order.

A faster way to convert a Map structure into an array structure is to use the extension operator (…). In addition, Map can be traversed through forEach.

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

3.3 Interconversion with other data structures

1. Map is converted into an array

By extending the operator (…)

2. Convert an array to a Map

The array is converted to a Map by passing it to the Map constructor

new Map([
  [true, 7],
  [{foo: 3}, ['abc']]
])
Copy the code
3. Map is converted into an object

If the Map’s keys are all strings, it can be converted to an object losslessly, and if there is a non-string key, the key name is converted to a string and used as the object’s key name.

4. Convert the object to Map
5. Convert the Map to JSON

There are two different cases of Map conversion to JSON. In one case, Map keys are all strings, and you can choose to convert to object JSON. Alternatively, if the Map has a non-string key name, you can choose to convert it to an array JSON

6. Convert JSON to Map

JSON to Map. Normally, all key names are strings. However, there is a special case where the entire JSON is an array, and each array member itself is an array with two members. In this case, it can be converted into a Map.

4. WeakMap

WeakMap structure is similar to Map structure and is also used to generate a set of key-value pairs

Difference 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 pointed to by the key name of WeakMap is not included in the garbage collection mechanism.Copy the code

If we want to store unused data on an object, but create a reference to the object, if we do not need the two objects, we must manually delete them, otherwise the garbage collection mechanism will not free up the occupied memory.

WeakMap is designed to solve this problem, and its key names refer to objects that are weak references, meaning that the garbage collection mechanism does not take that reference into account. Therefore, as long as other references of the referenced object are cleared, the garbage collection mechanism will release the memory occupied by the object, that is to say, once it is no longer needed, the key name object and the corresponding key value pair in WeakMap will automatically disappear without manual deletion.

Note: WeakMap weakly references only the key name, not the key value. Key values are still normal references.

4.1 Syntax of WeakMap

There are two main differences between WeakMap and Map in API. First, there is no traversal operation (no keys, values and entries) and no size attribute. Because there is no way to list all the key names, the existence of a particular key name is completely unpredictable and depends on whether the garbage collection mechanism is running. One moment the key name is available, the next garbage collection mechanism suddenly runs, and the key name is gone. To prevent uncertainty, there is a uniform rule that key names cannot be taken. The other is not the case, that is, the clear method is not supported. So WeakMap has four methods: get(), set(), has(), delete()

const wm = new WeakMap(); Wm. Size // undefined wm. ForEach // undefined wm. Clear // undefined wmCopy the code

4.2 Uses of WeakMap

  1. Applies to DOM nodes as key names
  2. Another use of WeakMap is to deploy private properties
  3. Is to prevent the risk of memory leaks

Welcome to pay attention to the public account [Xiaoyao students]

Re-learn js series

Relearn JS JavaScript introduction

Relearn JS to use JavaScript in HTML

Data types => Data types

Relearn the basic JavaScript concepts of JS (middle) => operator

Relearn the basic JavaScript concepts of JS (part 2) => operator

Relearn JavaScript variables, scope, and memory issues in JS

ES6 Introduction series

ES6 Introduction to let and cont

ES6 introduction to variable deconstruction assignment

ES6 starter string extension

ES6 – An extension to get started with re

ES6 introduction to numerical extension

Extension of ES6 introductory functions

ES6 introduction to the array extension

Extensions to ES6 starter objects

New methods for ES6 entry objects

ES6 Symbol for beginners

Git tutorial

Front-end Git basics tutorial