During development, we used the Array reference data structure a lot, knowing that an Array is an ordered collection and that each element can be retrieved as a numeric subscript. However, in some business scenarios, we do not need the collection to maintain an ordered state, and even some scenarios require an unordered Set. Therefore, THE unordered Set Set and its Weak version WeakSet are added in ES6.

In fact, the concept of unordered set is very easy to understand. We can think of it as an array without the concept of sorting, and it has the property that elements cannot be repeated.

This article will be introduced from the following aspects:

  • Set code example
  • The difference between Set and Array
  • Set common methods
  • WeakSet introduction

The reading time for this article is expected to be 5 minutes

Set code example

Set requires the new syntax new Set() declaration, which looks like this:

let set = new Set("Hello!!!");
set.add(12); //add 12
console.log(set.has("!")); //check if value exists
console.log(set.size);
set.delete(12); //delete 12
console.log(... set); set.clear();/ / delete all values"
//output
//true
/ / 6
//H e l o !Copy the code

In this code, we add a string and a number to the Set. The string is divided into characters for storage in the Set. Due to the characteristics of the Set, l and! Set {‘h’, ‘e’, ‘l’, ‘o’,’! ‘}), uses the add method to add 12 to the Set, so the Set size is 6.

The difference between Set and Array

The following table shows the differences between Array and Set

Compare the item Array Set
Elements in the sequence The orderly A disorderly
Element repeatability Element repeatability Elements are not repeatable

Set common methods

The following table lists the Set related methods

methods introduce
set.add(value) Adds elements to the collection
set.delete(value) Removes the specified element of the element
set.clear() Clears the collection of elements
set.forEach(callbackFn,[,context]) Iterates through all the elements in the collection and is called as an argument to CallbackFn
set.has(value) Checks whether the collection contains an element

Add delete Delete Delete

const set=new Set(a); set .add(1)
 .add(2)
 .add(3)
 .add(3);// It doesn't work because 3 is already in the set
console.log(set);//output Set { 1, 2, 3 }

// Delete elements
set.delete(2);
console.log(set);/ / the output Set {1, 3}

// Clear the collection
set.clear();
console.log(set); //output Set{}
Copy the code

Check the element

Because there is no sorting concept in Set, we cannot use the method of Array IndexOf to determine whether an element is greater than 0 to check whether an element is contained. ES6 uses a more concise and understandable method to check whether an element is contained.

const set=new Set([1.2.3.4]);
set.has(2) //output true;
set.has(5) //output false;
Copy the code

Traverse elements

The collection object itself defines a forEach method, just like the array forEach method.

const set=new Set([1.2.3.4]);
set.forEach(item= >{
  console.log(item);
})
//output
/ / 1
/ / 2
/ / 3
/ / 4
Copy the code

WeakSet introduction

JavaScript garbage collection is a memory management technique. In this technique, objects that are no longer referenced are automatically deleted and the resources associated with them are reclaimed. References to objects in a Set are strongly typed and do not allow garbage collection. As a result, if the Set references large objects that are no longer needed, such as DOM elements that have been removed from the DOM tree, recycling can be expensive.

To solve this problem, ES6 also introduces the WeakSet of WeakSet. These collections are “weak” because they allow objects referenced by these collections that are no longer needed to be purged from memory.

First of all, let us understand the difference between WeakSet and Set. The following three points are the differences between WeakSet and Set:

  1. A Set can store value types and object reference types, whereas a WeakSet can store only object reference types, otherwise a TypeError will be thrown.
  2. WeakSet cannot contain objects that have no reference, otherwise it will be automatically purged from the collection (garbage collection mechanism).
  3. A WeakSet object is non-enumerable, meaning you can’t get its size or the elements it contains.

The following code verifies the above features:

let weakset = new WeakSet(a); (function(){ 
   let a = {}; 
   weakset.add(1); //TypeError: Invalid value used in weak setweakset.add(a); }) ();//here 'a' is garbage collected from weakset
console.log()
console.log(weakset.size); //output "undefined"
console.log(... weakset);//Exception is thrown
weakset.clear(); //Exception, no such function
Copy the code
const weakset=new WeakSet(a);let foo={bar:1};
weakset.add(foo);
console.log(weakset.has(foo)); //output true
foo=null;
console.log(weakset.has(foo)); //output false
Copy the code

section

Today’s content is introduced here. In the future business, we can not only use Array, but also use Set and WeakSet. If there are no business scenarios where sorting needs to be de-weighted, we can try using set. If you want to optimize the program memory usage, you can try using WeakSet.

ES6 Basics Let and scope

【ES6 basics 】 Const introduction

ES6 Basics Default value

【ES6 分 】 Spread syntax

【ES6 Basics 】 Destructuring Assignment

【ES6 basics 】 Arrow functions

【ES6 Basics 】 Template String

More exciting content, please pay attention to the wechat “front-end talent” public number!