Home  >  Article  >  Web Front-end  >  What does es6 set mean?

What does es6 set mean?

青灯夜游
青灯夜游Original
2022-03-09 18:28:122028browse

set means "set" and is a new data structure provided by ES6. It is similar to an array, but the values ​​of the members are unique and there are no duplicate values. Set objects allow users to store unique values ​​of any type, whether primitive values ​​or object references.

What does es6 set mean?

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

What is Set?

Set (set) is a new data structure provided by ES6, which is similar to an array, but the values ​​of the members are unique and there are no duplicate values.

Set objects allow you to store unique values ​​of any type, whether primitive values ​​or object references.

Set itself is a constructor used to generate the Set data structure.

Special values ​​in Set:

The value stored in a Set object is always unique, so it is necessary to determine whether the two values ​​are equal. There are several special values ​​that require special treatment:

  • 0 and -0 are identical when storing and judging uniqueness, so they are not repeated;

  • undefined and undefined are identical, so they are not repeated;

  • NaN and NaN are not identical, but only one can be stored in the Set, and they are not repeated.

Set usage scenarios

1. Used for array deduplication

let arr = [3, 5, 2, 2, 5, 5];
let setArr = new Set(arr)     // 返回set数据结构  Set(3) {3, 5, 2}

//方法一   es6的...解构
let unique1 =  [...setArr ];      //去重转数组后  [3,5,2]

//方法二  Array.from()解析类数组为数组
let unique2 = Array.from(setArr )   //去重转数组后  [3,5,2]

2. Used for string deduplication

let str = "352255";
let unique = [...new Set(str)].join("");     // 352

3. Implement intersection, union and difference set

let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);

// 并集
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}

// 交集
let intersect = new Set([...a].filter(x => b.has(x)));
// set {2, 3}

// (a 相对于 b 的)差集
let difference = new Set([...a].filter(x => !b.has(x)));
// Set {1}

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of What does es6 set mean?. For more information, please follow other related articles on the PHP Chinese website!

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