Detailed explanation of JavaScript's Set data structure

Detailed explanation of JavaScript's Set data structure

1. What is Set

Set can be simply thought of as a mathematical set.

It is an unordered collection of data with no repeated values .

2. Set Constructor

For the parameters of the Set constructor, the following forms can be passed.

2.1) Arrays

 const s = new Set([1, 2, 1]);
console.log(s);

insert image description here

Here, an array [1, 2, 1] is passed as a parameter. Since Set is a collection of non-repeating values, the third 1 is automatically deleted.

2.2) Strings

 const s = new Set("Hello World!");
console.log(s);

insert image description here

2.3) arguments

 function fun() {
    const s = new Set(arguments);
    console.log(s);
}

fun(1, 2, 3);

insert image description here

2.4) NodeList

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>set</title>
</head>
<body>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    
    <script>
        const s = new Set(document.querySelectorAll('p'));
        console.log(s);
    </script>
</body>
</html>

insert image description here

Here, references to three p tags are placed into Set s;

When we need to use it, we can traverse this Set , and then take out the references of the p tags respectively, and then we can modify p tags.

2.5) Set

 const s1 = new Set([1, 2, 3]);
const s2 = new Set(s1);
console.log(s2);

insert image description here

This is equivalent to copying s1 and giving it to s2 , but they are not the same Set

 console.log(s1 === s2); 

insert image description here

3. Set instance properties and methods

The properties of Set have an attribute size , which is used to store the number of its members.

 const s = new Set([1, 2, 3]);
console.log(s.size);

insert image description here

Methods of Set

add

Adding members to a Set

 const s = new Set([1, 2, 3]); // It can only pass one parameter s.add(5); console.log(s); // It can be concatenated adds.add(7).add(9); console.log(s); 

insert image description here

delete

Used to delete members from a Set

 const s = new Set([1, 2, 3]);
s.delete(2);
// If the item to be deleted is not found in the Set, nothing will happen and no error will be reported s.delete(5);
console.log(s);

insert image description here

has

Used to determine whether a Set contains a member

 const s = new Set([1, 2, 3]);
console.log(s.has(1));
console.log(s.has(5));

insert image description here

clear

Will delete all members of the Set

 const s = new Set([1, 2, 3]);
s.clear();
console.log(s);

insert image description here

4. Set member access

Its member access is implemented through the forEach method, which traverses the Set in the order in which the members were added .

It has two parameters, the first parameter is the callback function, and the second parameter sets what this in the callback function points to, that is

 s.forEach(callback function, pointer to callback function)

Let's look at the first parameter:

For the first parameter callback function, it has three parameters:

 s.forEach(function(value, key, set){
	value is a member of Set. In Set, value and key are equal. Set is the previous Set itself, that is, here set === s
});

Let's understand it through an example:

 const s = new Set([1, 2, 3]);
s.forEach(function(value, key, set) {
    console.log(value, key, value === key);
    console.log(set, set === s);
});

insert image description here

Let's look at the second parameter:

 const s = new Set([1, 2, 3]);
s.forEach(function(value, key, set) {
    console.log(this);
}, document);

insert image description here

5. Notes on Set

Set's judgment on duplicate values ​​basically follows the strict equality === judgment

However, for NaN , in Set, NaN is equal to NaN

6. Use cases of Set

Array deduplication

 let arr = [1, 2, 1];
const s = new Set(arr);
arr = [...s];
// You can also combine them into one sentence // arr = [...new Set(arr)];
console.log(arr);

insert image description here

String deduplication

 let str = "11231131242";
const s = new Set(str);
str = [...s].join("");
// Can also be written as one sentence // str = [...new Set(str)].join("");
console.log(str);

insert image description here

Storing DOM elements

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>set</title>
</head>
<body>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    
    <script>
        const s = new Set(document.querySelectorAll('p'));
        s.forEach((elem) => {
            console.log(elem)
        });
    </script>
</body>
</html>

insert image description here

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • JS hash table collision handling, open chain method, HashTable hashing example
  • JS uses the reduce() method to process tree structure data
  • Detailed explanation of JavaScript's Set data structure
  • Convert Go language data structure to JSON
  • Detailed explanation of Map data structure in JavaScript
  • JavaScript Data Structure Number
  • JavaScript data structure: creation of hash table

<<:  The best 9 foreign free picture material websites

>>:  A brief analysis of the usage of HTML float

Recommend

How to install docker under centos and remotely publish docker in springboot

Table of contents 1. Installation of JDK1.8 under...

Write a publish-subscribe model with JS

Table of contents 1. Scene introduction 2 Code Op...

Docker cleaning killer/Docker overlay file takes up too much disk space

[Looking at all the migration files on the Intern...

Summary of how to add root permissions to users in Linux

1. Add a user . First, use the adduser command to...

Use Firebug tool to debug the page on iPad

How to debug a page on iPad? When using iOS 5, you...

Understanding of CSS selector weight (personal test)

Copy code The code is as follows: <style type=...

Sharing of the fast recovery solution for Mysql large SQL files

Preface In the process of using MySQL database, i...

Vue implements local storage add, delete and modify functions

This article example shares the specific code of ...

Tutorial on installing mongodb under linux

MongoDB is cross-platform and can be installed on...

How to use the debouce anti-shake function in Vue

Table of contents 1. Anti-shake function 2. Use d...

Analyze the selection problem of storing time and date types in MySQL

In general applications, we use timestamp, dateti...

A practical record of an accident caused by MySQL startup

Table of contents background How to determine whe...

Vue3 + TypeScript Development Summary

Table of contents Vue3 + TypeScript Learning 1. E...

Detailed explanation of the core concepts and basic usage of Vuex

Table of contents introduce start Install ① Direc...