new Set与...new Set()的区别

简介: new Set与...new Set()的区别,妙用多多

1. Set方法使用

方法 描述
add 添加某个值,返回Set对象本身。
clear 删除所有的键/值对,没有返回值。
delete 删除某个键,返回true。如果删除失败,返回false。
forEach 对每个元素执行指定操作。
has 返回一个布尔值,表示某个键是否在当前 Set 对象之中。

2. new Set()

new Set()本质,将数组/字符串转化为对象,且去重

//    数组转对象且去重
let arr = [1,2,3,3,1,4];
    let arrToObj = new Set(arr);
    console.log("arrToObj",arrToObj);//{ 1, 2, 3, 4 }
//    字符串转对象且去重
    let strToObj = new Set("ababbc");
    console.log("strToObj",strToObj);//{ 'a', 'b', 'c' }

3. ...new Set()

去重并转化为数组输出

//数组去重,生成新数组
    let noDouble =  [...new Set(arr)]; 
    console.log("noDouble",noDouble)// [1, 2, 3, 4]

//字符串去重    且转化为字符串
    let str = [...new Set('ababbc')]; // "abc" 字符串去重
    console.log("str",str)//abc

4.特殊操作

4.1 数组并集

    let array1 = new Set([1, 2, 3]);
    let array2 = new Set([4, 3, 2]);
    let unionObj = new Set([...array1, ...array2]); // {1, 2, 3, 4}
    console.log("unionObj",unionObj)
    let unionArray = [...new Set([...array1, ...array2])]; // [ 1, 2, 3, 4 ]
    console.log("unionArray",unionArray)

4.2 数组交集

    let array1 = new Set([1, 2, 3]);
    let array2 = new Set([4, 3, 2]);
    let intersectionObj = new Set([...array1].filter(x => array2.has(x))); // { 2, 3 }
    console.log("intersectionObj",intersectionObj)
    let intersectionArray = [...new Set([...array1].filter(x => array2.has(x)))]; // [ 2, 3 ]
    console.log("intersectionArray",intersectionArray)

4.3 数组差集

    let array1 = new Set([1, 2, 3]);
    let array2 = new Set([4, 3, 2]);
    let diffObj = new Set([...array1].filter(x => !array2.has(x))); // { 1 }
    console.log("diffObj",diffObj)
    let diffArray = [...new Set([...array1].filter(x => !array2.has(x)))]; // [ 1 ]
    console.log("diffArray",diffArray)
目录
相关文章
|
6天前
|
存储 JavaScript 索引
js开发:请解释什么是ES6的Map和Set,以及它们与普通对象和数组的区别。
ES6引入了Map和Set数据结构。Map的键可以是任意类型且有序,与对象的字符串或符号键不同;Set存储唯一值,无重复。两者皆可迭代,支持for...of循环。Map有get、set、has、delete等方法,Set有add、delete、has方法。示例展示了Map和Set的基本操作。
17 3
|
26天前
|
存储 JavaScript 前端开发
set和map的区别
set和map的区别
38 4
|
3月前
|
存储 JavaScript 前端开发
JavaScript 中 Set 和 Map 的区别
JavaScript 中 Set 和 Map 的区别
24 0
|
9月前
|
存储 开发者 索引
List 和 Set 集合的区别
List 和 Set 集合的区别
74 0
|
9月前
|
存储 容器
set和map的区别
set和map的区别
82 0
|
4月前
|
存储 索引 Python
python数据结构,集合(set)和字典(dict)之间的主要区别是什么?
python数据结构,集合(set)和字典(dict)之间的主要区别是什么?
|
4月前
|
存储 前端开发 索引
前端知识笔记(三)———Map和Set有什么区别?
前端知识笔记(三)———Map和Set有什么区别?
37 0
|
6月前
|
存储 Java 索引
每日一道面试题之list和set有什么区别?
每日一道面试题之list和set有什么区别?
|
7月前
|
JavaScript
js 中 Map 和 Set 区别
js 中 Map 和 Set 区别
|
10月前
|
索引 Python
pandas中set_index、reset_index区别
pandas中set_index、reset_index区别