new Set()的基础用法(ES6)

1、什么是Set()

似于数组,但它的一大特性就是所有元素都是唯一的,没有重复。
我们可以利用这一唯一特性进行数组的去重工作

2、常用方法

2.1 添加元素 add
let list=new Set();
list.add(1)
2.2 删除元素 delete
let list=new Set([1,20,30,40])
list.delete(30)      //删除值为30的元素,这里的30并非下标
2.3 判断某元素是否存在 has
let list=new Set([1,2,3,4])
list.has(2)//true
2.4 清除所有元素 clear
let list=new Set([1,2,3,4])
list.clear()
2.5 遍历 keys()
let list2=new Set(['a','b','c'])
for(let key of list2.keys()){
   console.log(key)//a,b,c
}
2.4 遍历 values()
let list=new Set(['a','b','c'])
for(let value of list.values()){
console.log(value)//a,b,c
}
2.5 遍历 forEach()
let list=new Set(['4','5','hello'])
list.forEach(function(item){
  console.log(item)
})
2.6 数组转Set (用于数组去重)
let set2 = new Set([4,5,6])
2.7 Set转数组
let set4 = new Set([4, 5, 6])
//方法一   es6的...解构
let arr1 =  [...set4];
//方法二  Array.from()解析类数组为数组
let arr2 = Array.from(set4)

参考链接 https://blog.csdn.net/qq_40016476/article/details/80999335

你可能感兴趣的:(ES6)