Home > Web Front-end > JS Tutorial > How to use es6 set

How to use es6 set

藏色散人
Release: 2023-01-11 09:19:43
Original
2894 people have browsed it

es6 How to use set: 1. Define from var to let through "let a=[1,2,3,4,5];"; 2. Through "let set=new Set( );" syntax is set.

How to use es6 set

The operating environment of this article: Windows 7 system, ECMAScript version 6, Dell G3 computer.

How to use es6 set?

The usage of set in es6

is as follows:

//定义从var变为let 不可重复定义
let a=[1,2,3,4,5];

// Set 它类似于数组,但是成员的值都是唯一的,没有重复的值。

    let set=new Set();
Copy after login

Set instance methods are divided into two categories: Operation methods (for operating data) and traversal methods (for traversing members).

The following will introduce four operation methods.

add(value): Add a value and return the Set structure itself.

delete(value): Delete a value and return a Boolean value indicating whether the deletion was successful.

has(value): Returns a Boolean value indicating whether the value is a member of Set.

clear(): Clear all members, no return value.

The Array.from method can convert the Set structure into an array.

Instances of the Set structure have four traversal methods that can be used to traverse members.

keys(): Returns the traverser of key names

values(): Returns the traverser of key values ​​

entries(): Returns the key-value pair Traverser

forEach(): Use the callback function to traverse each member

It should be noted that the traversal order of Set is the insertion order.

Since the Set structure has no key names, only key values ​​(or the key name and key value are the same value), the behaviors of the keys method and the values ​​method are exactly the same.

Instances of the Set structure can be traversed by default, and its default traverser generation function is its values ​​method.

This means that the values ​​method can be omitted and the for...of loop is used to traverse the Set directly.

The spread operator (...) uses for...of loop internally, so it can also be used for Set structure.

Example

//1 数组去重
let a=[1,2,3,4,5,6,7,1,2,3];
let b=new Set([...a]);
b=[...b];
// 2 求交集 并集  差集
let a=new Set[1,2,3];
let b=new Set[3,4,5];
//交集
let c=new Set([...a,...b]);
//并集
let d=new Set([...a].filter(x=>b.has[x]));
//交集
let d=new Set([...a].filter(x=>!b.has[x]));
Copy after login

Recommended study: "javascript basic tutorial"

The above is the detailed content of How to use es6 set. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template