Set collection and Map mapping in ES6

Article directory

  • 1. Set collection
    • 1.Basic use of Set
    • 2. Common methods of Set
    • 3.WeakSet usage
    • 4.Application of WeakSet
  • 2. Map mapping
    • 1.Basic use of Map
    • 2. Common methods of Map
    • 3.WeakMap usage
    • 4.Application of WeakMap
  • 3. Description of other knowledge points of ES6

1. Set collection

1.Basic use of Set

Before ES6, there were two main structures for storing data: arrays and objects.

Two other data structures were added in ES6: Set, Map, and their other forms WeakSet, WeakMap code>.

Set is a new data structure that can be used to save data, similar to array, but the difference from array is that elements cannot be repeated.

To create a Set we need to pass the Set constructor (there is currently no way to create a literal):

const s1 = new Set()
const arr = [3, 45, 3]
const s2 = new Set(arr)
console.log(s2)// 3, 45

We can find that the elements stored in Set will not be repeated, so Set has a very common function of deduplicating arrays.

const arr1 = [3, 4, 6]
const s3 = new Set(arr1)
const arr2 = [...s3]
const srr3 = Array.from(s3)

2. Common methods of Set

Set common properties:

  • size: Returns the number of elements in the Set;

Set commonly used methods:

  • add(value): Add an element and return the Set object itself;
  • delete(value): Delete the element equal to this value from the set and return the boolean type;
  • has(value): Determine whether an element exists in the set and return a boolean type;
  • clear(): Clear all elements in the set, no return value;
  • forEach(callback, [, thisArg]): Traverse set through forEach;

In addition, Set supports for-of traversal.

// 1. Create Set
const set = new Set()
console.log(set)

// 2. Add elements
set.add(10)
set.add(22)
set.add(35)
set.add(22)
console.log(set)

const info = {<!-- -->}
const obj = {<!-- -->name: "obj"}
set.add(info)
set.add(obj)
set.add(obj)
console.log(set)

// 3. Application scenario: Array deduplication
const names = ["abc", "cba", "nba", "cba", "nba"]
// const newNames = []
// for (const item of names) {<!-- -->
// if (!newNames.includes(item)) {<!-- -->
// newNames.push(item)
// }
// }
// console.log(newNames)
const newNamesSet = new Set(names)
const newNames = Array.from(newNamesSet)
console.log(newNames)

// 4. Other properties and methods of Set
// Attributes
console.log(set.size)
// method
// 4.1. add method
set.add(100)
console.log(set)
// 4.2. delete method
set.delete(obj)
console.log(set)
// 4.3. has method
console.log(set.has(info))
// 4.4. clear method
// set.clear()
// console.log(set)
// 4.5. forEach
set.forEach(item => console.log(item))

// 5.set supports for...of
for (const item of set) {<!-- -->
    console.log(item)
}

3.Using WeakSet

Another data structure similar to Set is called WeakSet, which is also a data structure whose internal elements cannot be repeated.

So what is the difference from Set?

  • Difference 1: WeakSet can only store object types, cannot store basic data types;
  • Difference 2: The reference of WeakSet to the element is weak reference. If there is no other reference to an object, then GC can recycle the object;

Common methods of WeakSet:

  • add(value): Add an element and return the WeakSet object itself;
  • delete(value): Delete elements equal to this value from WeakSet, returning boolean type;
  • has(value): Determine whether an element exists in WeakSet and return boolean type;

4.Application of WeakSet

Note: WeakSet cannot be traversed

  • Because WeakSet is only a weak reference to the object, if we traverse to obtain the elements, the object may not be destroyed normally.

  • Therefore, the objects stored in WeakSet cannot be obtained;

So what is the use of this thing?

  • In fact, this question is not easy to answer. Let’s use an answer on Stack Overflow;
// 3. Application of WeakSet
const pWeakSet = new WeakSet()
class Person {<!-- -->
    constructor() {<!-- -->
        pWeakSet.add(this)
    }

    running() {<!-- -->
        if (!pWeakSet.has(this)) {<!-- -->
            console.log("Type error: The calling method is wrong")
            return
        }
        console.log("running~")
    }
}

let p = new Person()
// p = null
p.running()
const runFn = p.running
runFn()
const obj = {<!-- --> run: runFn }
obj.run()

2. Map mapping

1.Basic use of Map

Another new data structure is Map, which is used to store mapping relationships.

But we may think, before we could use objects to store mapping relationships, what is the difference between them?

In fact, our object storage mapping relationship can only use string (ES6 has added Symbol) as the attribute name (key);

In some cases, we may want to use other types as keys, such as objects. In this case, the object will be automatically converted into a string as the key;

Then we can use Map:

const info = {<!-- --> name: "why" }
const info2 = {<!-- --> age: 18 }

// 1. Limitations of object types: complex types cannot be used as keys
// const obj = {<!-- -->
// address: "Beijing",
// [info]: "Hahaha",
// [info2]: "Hehehe"
// }
// console.log(obj)

// 2.Map mapping type
const map = new Map()
map.set(info, "aaaa")
map.set(info2, "bbbb")
console.log(map)

// 3. Common properties and methods of Map
// console.log(map.size)
// 3.1. set method, set content
map.set(info, "cccc")
console.log(map)
// 3.2. get method, get content
// console.log(map.get(info))
// 3.3. delete method, delete content
// map.delete(info)
// console.log(map)
// 3.4. has method, determine content
// console.log(map.has(info2))
// 3.5. clear method, clear content
// map.clear()
// console.log(map)
// 3.6. forEach method
// map.forEach(item => console.log(item))

// 4.for...of traversal
for (const item of map) {<!-- -->
    const [key, value] = item
    console.log(key, value)
}

2. Common methods of Map

Map common attributes:

  • size: Returns the number of elements in the Map;

Common methods of Map:

  • set(key, value): Add key and value to the Map and return the entire Map object;
  • get(key): Get the value in the Map based on the key;
  • has(key): Determine whether a certain key is included and return Boolean type;
  • delete(key): delete a key-value pair based on key and return Boolean type;
  • clear(): clear all elements;
  • forEach(callback, [, thisArg]): Traverse Map through forEach;

Map can also be traversed through for-of.

3.WeakMap usage

Another data structure of the Map type is called WeakMap, which also exists in the form of key-value pairs.

So what is the difference from Map?

  • Difference 1: WeakMap’s key can only use objects and does not accept other types as keys;
  • Difference 2: The reference of the WeakMap key to the object is weak reference. If there is no other reference to the object, then the GC can recycle the object;

There are four common methods of WeakMap:

  • set(key, value): Add key and value to the Map and return the entire Map object;
  • get(key): Get the value in the Map based on the key;
  • has(key): Determine whether a certain key is included and return Boolean type;
  • delete(key): delete a key-value pair based on key and return Boolean type;
let obj1 = {<!-- --> name: "why" }
let obj2 = {<!-- --> name: "kobe" }

// 1.Basic use of WeakMap
const weakMap = new WeakMap()
// weakMap.set(123, "aaa")
weakMap.set(obj1, "aaa")
weakMap.set(obj2, "bbb")

obj1 = null
obj2 = null

4.Application of WeakMap

Note: WeakMap cannot be traversed either.

  • There is no forEach method, and it does not support traversal through for-of;

So what does our WeakMap do? (Special explanation will be given later)

Vue’s responsive source code

3. Description of other knowledge points of ES6

In fact, ES6 (ES2015) is a very big version update, so there are many important features in it:

In addition to the features mentioned earlier, there are many other features;

1.Proxy, Reflect

  • We will learn more about it later.

  • And will use Proxy and Reflect to explain the responsiveness principle of Vue3;

2.Promise

  • Solutions for handling asynchrony, which will be studied in detail later;

  • And will learn how to write Promise by hand;

3.ES ModuleModular development:

  • Developed from ES6, JavaScript can be developed natively and modularly;
  • This part of the content will be studied in the engineering part;
  • Including other modular solutions: CommonJS, AMD, CMD and other solutions;