1.对数组进行去重操作:
let arr = [1, 1, 2, 2, 3, 3]
arr = new Set(arr)
console.log([...arr]) //[1, 2, 3]
//使用展开符才能正确输出为数组,否则为Set对象
2.取两个或多个数组的并集:(合并多个数组并去重)
let arr = [1, 1, 2, 2, 3, 3]
let arr1 = [1, 2, 4, 5]
arr = new Set(arr)
arr1 = new Set(arr1)
for(let x of arr1) {
if(!arr.has(x)) { //has()判断是否存在
arr = arr.add(x) //add()添加操作
}
}
console.log([...arr]) //[1, 2, 3, 4, 5]
3.取交集:
let arr = [1, 1, 2, 2, 3, 3]
let arr1 = [1, 2, 4, 5]
let newarr = new Set() //新建一个Set对象开存储交集
arr = new Set(arr)
arr1 = new Set(arr1)
for(let x of arr1) {
if(arr.has(x)) {
newarr = newarr.add(x)
}
}
console.log([...newarr]) //[1, 2]