使用ES6中new Set() 方法去重 new Set()的基础使用
dearweb
发布:2021-09-16 18:33:03阅读:
不少前端小伙伴在开发的过程中一定会遇到数组的去重处理吧!今天小编给大家介绍的是ES6中的方法new Set(),不仅可以快速去重而且还能进行数组的并集、差集和交集计算。
数组去重的用法
这是我们工作中用到的比较多的一种方法。
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]其次我们还可以用于字符去重
let str = "352332522566";
let unique = [...new Set(str)].join(""); // 3526实现数组的并集、交集、和差集
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}除了上面介绍的最常用的几种方法外,set()中还有增删改查以及遍历的方法,下面小编给大家一一介绍。
遍历方法
遍历 keys():返回键名的遍历器,相等于返回键值遍历器values()
let list2=new Set(['a','b','c'])
for(let key of list2.keys()){
console.log(key)//a,b,c
}遍历 values():返回键值的遍历器
let list=new Set(['a','b','c'])
for(let value of list.values()){
console.log(value)//a,b,c
}遍历 entries():返回键值对的遍历器
let list=new Set(['4','5','hello'])
for (let item of list.entries()) {
console.log(item);
}
// ['4','4'] ['5','5'] ['hello','hello']遍历 forEach():使用回调函数遍历每个成员
let list=new Set(['4','5','hello']) list.forEach( (value, key) => console.log(key + ' : ' + value) ) // 4:4 5:5 hello:hello
数组的增删改查
添加元素-----add()
添加某个值,返回 Set 结构本身,当添加实例中已经存在的元素,set不会进行处理添加
let list=new Set();
list.add(1) // {1}
list.add(2).add(3).add(3) // {1, 2, 3} // 3只被添加了一次删除元素-----delete()
删除某个值,返回一个布尔值,表示删除是否成功
let list=new Set([1,20,30,40])
list.delete(30) // true //删除值为30的元素,有返回true,没有返回false
console.log(list) // {1, 20, 40}判断某元素是否存在-------has()
返回一个布尔值,判断该值是否为Set的成员
let list=new Set([1,2,3,4]) list.has(2) // 有返回true,没有返回false
清除所有元素------clear()
清除所有成员,没有返回值
let list=new Set([1,2,3,4])
list.clear()
console.log(list) // {}小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧