search
HomeWeb Front-endJS TutorialHow to use Set and WeakSet_javascript techniques in ES6

ES6 provides two new data structures-Set and WeakSet. Set is similar to an array, but the values ​​of member variables are unique and there are no duplicate values. WeakSet is also a collection of unique values, but it can only be used to store objects.

1. Use of Set

(1)Set itself provides a constructor to generate the Set data structure.

var s = new Set();
[2,2,2,5,8,16,2,1].map(x => s.add(x))

for(i of s){console.log(i)}
//2,5,8,16,1

(2) The Set() function can accept an array as a construction parameter for initialization.

var s = new Set([1,2,3,4,2,4,3]);
[...s]
//[1,2,3,4]

Note: Type conversion does not occur when adding a value to a Set, so 5 and "5" are two different values. Set internally determines whether the two values ​​​​are equal, using = ==, which means the two objects are always not equal. The only thing outside the list is NaN itself (the exact equality operator considers NaN not equal to itself)

let set = new Set();
set.add({})
set.size//1
set.add({})
set.size//2

Then, the above code means that since the two empty objects are not exactly equal, they have two different values.

(3)Set methods and attributes

(3.1)Set attributes

Set.prototype.size: Returns the number of members of the Set instance.
Set.prototype.constructor: The default constructor Set function.

(3.2)Set operation function

add(value): Add a value and return the Set structure itself.
delete(value): Delete a certain value and return a Boolean value indicating successful deletion.
has(value): Returns a Boolean value indicating whether the parameter is a member of Set.
clear(): Clear all members, no return value.

var set = new Set();
set.add(1).add(2).add(22).add(22);
set.size//3

set.hae(22)//true
set.has(4)//false
set.delete(2)//true

(3.3)Set traversal operation

Set has four traversal methods. Can be used to traverse members.
keys(): Returns a traverser of key names
values() : returns a value traverser
entries(): Returns a traverser of key-value pairs
forEach(): Use callback function to traverse each member

Note: Since Set has no key name, only value name, the results returned by keys() and values() are the same,

let set = new Set(['red','green','blue']);
for(let item of set.keys()){
console.log(item);
}
//red,green,blue
for(let item of set.values()){
console.log(item);
}
//red,green,blue
for(let item of set.entries()){
console.log(item);
}
//["red","red"]
//["green","green"]
//["blue","blue"]

//所以,entries方法返回的遍历器同时包括键名和值,所以每次输出的是一个数组。其实成员都是完全一样的。

Note: Set is traversable by default, and its default traverser generation function is its values ​​method.
This means that you can omit the values ​​method and directly use for...of to traverse.

var set = new Set([1,2,3,4]);
for(let x of set){
console.log(x);
}
//1
//2
//3
//4

If you use the spread operator (...), a for...of loop is used internally, so it can also be used for the Set structure.

let set = new Set(['red','green','blue']);
let arr = [...set];
//['red','green','blue'];

(3.4)Set implements union, intersection and difference set

let set1 = new Set([1,2,3,4,5,6]);
let set2 = new Set([4,5,6,7,8,9]);

//并集
let union = new Set([...set1,...set2]);
//[1,2,3,4,5,6,7,8,9]
//交集
let intersect = new Set([...set1].filter(x => b.has(s)));
//[4,5,6]
//差集
let intersect = new Set([...set1].filter(x => !b.has(s)));
//[1,2,3,4]

(3.5)Set implements the use of forEach

let set = new Set([1,2,3,4,5,6]);
set.forEach(value,key)=>consloe.log(vlaue+1);
//2
//3
//4
//5
//6
//7

Note: The parameter of the forEach method is a processing function, which in turn is the (key value, key name) collection itself. In addition, the forEach method has a second parameter, which represents the object to which this is bound.

2. Use of WeakSet

WeakSet is similar to Set and is also a collection of non-repeating values. But it can only be used to store objects. It cannot be any other type of value.
WeakSet is a constructor. Can accept arrays and array-like objects as arguments. (In fact, any object with an iterable interface can be used as a parameter of WeakSet). All members of the array will automatically become members of the WeakSet instance object.
var a = new [[1,2],[3,4]];
var ws = new WeakSet(a);

var ws = new WeakSet();
ws.add(1);//TypeError:Invalid value used in weak set 
ws.add(Symbol);//TypeError:Invalid value used in weak set 

Add a value and a Symbol, and an error will be reported at the same time.

The WeakSet structure has the following methods
WeakSet.protoptype.add(value): Add a new member to the WeakSet instance.
WeakSet.protoptype.delete(value): Delete the specified member of the WeakSet instance.
WeakSet.protoptype.has(value): Returns a Boolean value indicating whether a value is in a WeakSet instance.

var ws = new WeakSet();
var obj = {};
var foo = {};
ws.add(window);
ws.add(obj);
ws.has(window);//true
ws.has(foo);false
ws.delete(window);//true
ws.has(window);//false

WeakSet cannot be traversed because the members are weak references and may disappear at any time. Traversal cannot guarantee the existence of members. It may be that just after the traversal is completed, the members are no longer available. One use of WeakSet is to store DOM nodes without worrying about memory leaks when these nodes are removed from the document.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft