preface


I haven’t written any technical articles since I officially joined the company. I am busy every day. I would like to summarize the knowledge points of Set and Map reviewed during this period of time while I am free this weekend.

Prior to ES6, arrays were often used to create queues and stacks because of the limited collection types available and their use of numeric indexes. If we wanted to use non-numeric indexes, we would use non-array objects to create the required data structures, and this was an early implementation of sets and maps.

The body of the


Set

A Set is an ordered list of non-repeating elements. Usually, we use a Set to detect whether a given value exists in a Set.

How do we implement a set in ES5

var set = Object.create(null)

set.foo = true

// Check if the attribute exists
if (set.foo) {
  // The code to execute
}
Copy the code

Here the variable set is a null object that inherits no attributes. In ES5, we often use a similar method to check for the presence of an attribute value on an object. But it has the disadvantage of having to ensure that each key name is a string and unique within the object.

Create a Set collection and add elements

There are two ways to add sets, either by passing in an array with a new Set(), or by adding elements with an instance of.add()

let set1 = new Set()
set1.add(5)
set1.add("5")
console.log(set1.size) / / 2

let set2 = new Set([1.2.2.3.'4'])
console.log(set2.size) // 4, duplicate elements are ignored

let set3 = new Set(),
		key1 = {},
    key2 = {}

set3.add(key1)
set3.add(key2)
console.log(set3.size) / / 2
Copy the code

In a Set, there are no forced conversions to the stored values. The number 5 and the string ‘5’ can exist as two separate elements because the JavaScript engine uses the object.is () method internally.

The Set constructor accepts all iterable objects as arguments. Arrays, sets, and maps are all iterable and can therefore be used as arguments to the Set constructor, which extracts values from the arguments through iterators.

Detect and remove elements

Elements can also be checked with the has() method, which returns a Boolean, the delete() method removes an element, and the clear() method clears all elements.

let set = new Set([1.2.3.4.'5'])
console.log(set.has(2)) // true
console.log(set.has(9)) // false

set.delete('5')
console.log(set.has('5')) // false

set.clear()
console.log(set.has(2)) // false
Copy the code

We can also filter duplicate elements in an array using the Set Set, as follows:

const eliminateDuplicates = (arr) = > {
  return [...new Set(arr)]
}

const arr = [1.1.1.2.2.2.3.3.4.4.5.6]
console.log(eliminateDuplicates(arr)) / / [6]
Copy the code

The Weak Set is called the Weak Set. The Weak Set is called the Weak Set. The Weak Set is called the Weak Set. The Weak Set is called the Weak Set. The Weak Set is called the Weak Set.

Weak Set collection

Weak Set sets are strong references. An object stored in an instance of a Set is the same as an object stored in a variable. As long as a reference exists in a Set instance, the garbage collection mechanism cannot free the memory of the object

Let’s take a look at this code

let set = new Set(),
    key = {}

set.add(key)
console.log(set.size) / / 1

// Remove the original reference
key = null

console.log(set.size) / / 1

// Retrieve the original reference
key = [...set][0]
Copy the code

One important point here is that when we want to go to a Set, we can use forEach or we can use for… Of, or turn a Set into an array and index it.

As you can see, the Set retains a reference to the key even if the key has removed the original reference.

Create the Weak Set collection

The WeakSet constructor creates WeakSet collections that support three methods: add(), has(), and Delete ()

let set = new WeakSet(),
    key = {}

set.add(key)

console.log(set.has(key)) // true

set.delete(key)

console.log(set.has(key)) // false
Copy the code

Keep in mind that the WeakSet constructor does not accept any raw values, and the program will throw an error if the array contains other non-object values.

let key1 = {},
    key2 = {},
    set = new WeakSet([key1, key2])

console.log(set.has(key1)) // true

key2 = null
console.log(set.has(key2)) // false
Copy the code

Weak Set sets and Set sets

1. In the WeakSet instance, if non-object parameters are passed in the Add () method, the program will report an error, while non-object parameters are passed in the HAS () and DELETE () methods, false will be returned.

2.Weak Set sets are not iterable and therefore cannot be used for for-of loops

3. The Weak Set does not expose any iterators, so it cannot be verified by the program itself.

4. The Weak Set does not support the forEach method

5.Weak Set sets do not support the size attribute or the clear() method

Map collections

A Map collection is an ordered list of key-value pairs whose key names and corresponding values support all data types. The equivalence of key names is achieved by calling object.is (), so 5 and ‘5’ are identified as two types that can appear in programs as separate keys, unlike objects, whose property names are always cast to string classes.

Let’s start by simulating the Map collection with ES5

var map = Object.create(null)
map.foo = "bar"

// Get the saved value
var value = map.foo

console.log(value) // 'bar'
Copy the code

Create a Map collection and add elements

There are two ways to add key-value pairs to a Map collection. You can pass in an array using the Map constructor, or you can add elements using the instance method set(), which is evaluated by the get() method.

let map1 = new Map()
map1.set('title'.'hello es6')
map1.set('year'.2020)

console.log(map1.get('title')) // 'hello es6'
console.log(map1.get('day')) // undefined

let map2 = new Map([['title'.'hello es6'], ['year'.2020]])
console.log(map2.get(year)) / / 2020
Copy the code

Returns undefined if the key name passed through the get method does not exist.

Properties and methods supported by the Map collection

  • has(key)Checks whether the specified key name exists in the Map collection
  • delete(key)Deletes the specified key-value pair
  • clear()Clear all key-value pairs
  • forEach()The iteration
  • sizeThe key value logarithmic

Because these methods are relatively simple, I won’t go through the code here.

Like the Set collection, the Map collection is strongly referenced, so it has its Weak Map cousin.

Weak Map collections

The Weak Map collection is an unordered list that stores many key-value pairs. The key names of the list must be non-NULL objects, and the values corresponding to the key names can be of any type.

Weak Map and Weak Set are Weak references. Once the referenced object reference is empty, the Weak Map is automatically dereferenced to prevent memory leakage.

The Weak Map collection displays an error if it uses a non-object key name.

The Weak Map collection is most useful for holding DOM elements in Web pages.

Create the Weak Map collection

let map = new WeakMap(),
    element = document.querySelector('.element')
map.set(element, "Original")

let value = map.get(element)
console.log(value) // "Original"

// Remove element
element.parentNode.removeChild(element)
element = null

console.log(map.has(element)) // false
Copy the code

Like the Map collection, the WeakMap collection also supports the constructor passing in an array to create key-value pairs, but the key names must be non-NULL objects.

The Weak Map collection supports methods

  • has(key)Checks whether key-value pairs exist
  • delete(key)Delete key-value pairs
  • forEach()The iteration

Since these methods are relatively simple, I won’t attach the code snippets here.

Weak Map sets and Map sets

  • Since the WeakMap set does not support key name enumeration, the clear() method and size attribute are not supported
  • The key name of the Weak Map collection must be a non-NULL object
  • Weak Map collectionsDoes not supportforEach
  • The Weak Map set can effectively prevent memory leaks

conclusion


This is the end of the Set and Map Set explanation. I hope this article can help you. Thank you for watching