JavaScript has a deep understanding of – set, map, weakset and weakmap

Time:2021-6-20

Set

The set object allows you to store unique values of any type, whether they are original values or object references
Essence: constructor, used to generate set data structure

describe

A set object is a collection of values, and you can iterate its elements in the order in which they are inserted. The elements in the set will only appear once, that is, the set element is unique.
It is equivalent to a set and can be used for union intersection operation.

Equality of values

For the original data type (Boolean, number, string, null, undefined), if the same value is stored, only one will be saved. For the reference type, if the reference address is exactly the same, only one will be saved.

  • +0 and – 0 are identical when storing and judging uniqueness, so they can’t be repeated.
  • Undefined and undefined are identical, so they cannot be repeated.
  • Nan and Nan are not identical, but only one can be stored in the set and cannot be repeated.

Attribute method

  • Size attribute: returns the number of collection elements (similar to the length of an array)
  • Add (value) method: you want to add an element to the collection. If the added element already exists, the operation is not performed.
  • Delete (value) method: delete the element value from the collection
  • Has (value) method: judge whether value is in the collection and return true or false
  • Clear() method: clear the collection
  • Foreach() method: according to the insertion order of the elements in the collection, execute the provided callback function in turn

Application scenarios
Array de duplication, intersection, union, difference and so on

//Array de duplication
...new Set([1,1,2,2,3])

//Union
let arr1 = [1, 2, 3]
let arr2 = [2, 3, 4]
let newArr = [...new Set([...arr1, ...arr2])]
//Intersection
let arr1 = [1, 2, 3]
let arr2 = [2, 3, 4]
let set1 = new Set(arr1)
let set2 = new Set(arr2)
let newArr = []
set1.forEach(item => {
    set2.has(item) ? newArr.push(item) : ''
})
console.log(newArr)
//Difference set
let arr1 = [1, 2, 3]
let arr2 = [2, 3, 4]
let set1 = new Set(arr1)
let set2 = new Set(arr2)
let newArr = []
set1.forEach(item => {
    set2.has(item) ? '' : newArr.push(item)
})
set2.forEach(item => {
    set1.has(item) ? '' : newArr.push(item)
})
console.log(newArr)

Map

Map object saves key value pairs and can remember the original insertion order of keys. Any value (object or original value) can have a key or a value

Description:

A map object will be iterated according to the insertion order of the elements in the objectfor ofAfter each iteration, the loop returns a[key,value]Array of

Equality of keys

For the original data type (Boolean, number, string, null, undefined), if the same value is stored, only one will be saved. For the reference type, if the reference address is exactly the same, only one will be saved.

  • +0 and – 0 are identical when storing and judging uniqueness, so they can’t be repeated.
  • Undefined and undefined are identical, so they cannot be repeated.
  • Nan and Nan are not identical, but only one can be saved and cannot be repeated.

The difference between map and object

Map Object
Extra keys By default, map does not contain any keys, only the inserted ones An object has a prototype. The key name on the prototype chain may conflict with the key name set on the object. Es5 is applicableObject.create(null)To create an object without a prototype
Type of key The key of a map can be any value, including function, object or any basic type The key of an object must be a string or symbol
Key order The keys in a map are ordered, so when iterating, a map object returns the key values in the order of insertion The key of an object is unordered
Size Get it through the size attribute The key value of objec can only be calculated manually
iteration It can be iterated directly You need to get the key in some way to be iterated
performance It performs better in the scene of frequent addition and deletion of key value pairs No optimization

Attribute method

  • Size property: returns the length of the dictionary (similar to the length of an array)
  • Values() method: returns an iteratable object, which contains the value value of each element inserted into the map object in order
  • Set (key, value) method: add a new element to the dictionary
  • Get (key) method: find a specific value by key and return it
  • Has (key) method: judge whether there is a key in the dictionary
  • Delete (key) method: remove the corresponding data from the dictionary by key
  • Clear() method: clear dictionary
  • Foreach() method: according to the insertion order of the elements in the collection, execute the provided callback function in turn

ergodic

var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

for (const [key, value] of myMap) {
  console.log(key, value);
}

myMap.forEach((value, key) => {
  console.log(value, key);
});

transformation

var arr = [
  [1, 2],
  [3, 4],
  [5, 6],
];

var map = new Map(arr);
console.log(map); //Map { 1 => 2, 3 => 4, 5 => 6 }
console.log(Array.from(map)); //[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]

copy
let mapV=newMap(map)

WeakSet

The weakset object allows weak reference objects to exist in a collection

Difference between weakset and set:

  • Weakset can only store object references, not values, while set objects can
  • The object values stored in the weakset object are all weakly referenced, that is, the garbage collection mechanism does not consider the reference of the weakset to the object. If no other variable or attribute references the object value, the object will be garbage collected( The number of member elements in the weakset object depends on whether the garbage collection mechanism is running or not. The number of members before and after running may be inconsistent. After traversing, some members may not be retrieved and be garbage collected. Therefore, ES6 stipulates that the weakset object cannot be traversed, and there is no way to get all the elements it contains.

Properties:
Constructor: constructor
method:

  • Add (value) method: add an element to weakset. If the added element already exists, the operation is not performed.
  • Delete (value) method: delete the element value
  • Has (value) method: judge whether the weakset object contains value
  • Clear() method: clear all elements

WeakMap

A weakmap object is a collection of key values, where the key is a weak reference. Note: the key must be a weak reference and the value can be arbitrary.
Note: weakmap weakly references only the key name, not the key value. The key value is still a normal reference.

Difference between weakmap and map:
In weakmap, the reference of each key to its referenced object is weak. If there is no other reference and the key to the same object, the object will be garbage collected, and the corresponding key will become invalid. Therefore, the key of weakset cannot be enumerated.
Properties:
Constructor: constructor
method:

  • Set (key, value) method: set a group of key associated objects
  • Delete (key) method: remove the associated object of the key
  • Has (value) method: judge whether the weakset object contains value
  • Get (key) method: returns the key associated object, if not, undefined

summary

  • Set
    • Members are unique, unordered and non repetitive
    • Similar to array collection, the key value and key name are consistent (only the key value). No key name)
    • Can traverse, the method has add, delete, has
  • WeakSet
    • Only the corresponding reference can be stored, not the value
    • Members are weak references and will be recycled by garbage collection mechanism
    • Can not traverse, the method has add, delete, has
  • Map
    • The key name is unique and cannot be repeated
    • Similar to a set, a set of key value pairs, any value can be used as a key or a value
    • Can traverse, can convert a variety of data formats, methods get, set, has, delet
  • WeakMap
    • Only the object is accepted as the key name, and other types of values are not accepted as the key name. The key value can be arbitrary
    • The key name is a drag reference, and the object the key name points to will be recycled by the garbage collection mechanism
    • Cannot traverse, method get, set, has, delete