Home Web Front-end JS Tutorial How to use Set and WeakSet_javascript techniques in ES6

How to use Set and WeakSet_javascript techniques in ES6

May 16, 2016 pm 03:11 PM
es6 set

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

Copy after login

(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]
Copy after login

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
Copy after login

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方法返回的遍历器同时包括键名和值,所以每次输出的是一个数组。其实成员都是完全一样的。

Copy after login

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
Copy after login

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'];
Copy after login

(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]
Copy after login

(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
Copy after login

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 
Copy after login

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

Copy after login

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

How to reverse an array in ES6 How to reverse an array in ES6 Oct 26, 2022 pm 06:19 PM

In ES6, you can use the reverse() method of the array object to achieve array reversal. This method is used to reverse the order of the elements in the array, putting the last element first and the first element last. The syntax "array.reverse()". The reverse() method will modify the original array. If you do not want to modify it, you need to use it with the expansion operator "...", and the syntax is "[...array].reverse()".

Is async for es6 or es7? Is async for es6 or es7? Jan 29, 2023 pm 05:36 PM

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

How to find different items in two arrays in es6 How to find different items in two arrays in es6 Nov 01, 2022 pm 06:07 PM

Steps: 1. Convert the two arrays to set types respectively, with the syntax "newA=new Set(a);newB=new Set(b);"; 2. Use has() and filter() to find the difference set, with the syntax " new Set([...newA].filter(x =>!newB.has(x)))", the difference set elements will be included in a set collection and returned; 3. Use Array.from to convert the set into an array Type, syntax "Array.from(collection)".

Why does the mini program need to convert es6 to es5? Why does the mini program need to convert es6 to es5? Nov 21, 2022 pm 06:15 PM

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

How to implement array deduplication in es5 and es6 How to implement array deduplication in es5 and es6 Jan 16, 2023 pm 05:09 PM

In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

What does es6 temporary Zenless Zone Zero mean? What does es6 temporary Zenless Zone Zero mean? Jan 03, 2023 pm 03:56 PM

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

Is es6 map ordered? Is es6 map ordered? Nov 03, 2022 pm 07:05 PM

The map is ordered. The map type in ES6 is an ordered list that stores many key-value pairs. The key names and corresponding values ​​support all data types; the equivalence of key names is determined by calling the "Objext.is()" method. Implemented, so the number 5 and the string "5" will be judged as two types, and can appear in the program as two independent keys.

See all articles