Set
ES6 提供了新的数据结构 `Set` ,它类似与 **数组**,但成员的值都是**唯一**的,集合实现了 `iterator` 接口,所以可以使用 `...(拓展运算符)` 和 `for...of` 进行遍历,集合的属性和方法:
- size:返回集合的元素个数
- add:增加一个新元素,返回当前集合
- delete:删除元素,返回
boolean 值 - has:检测集合中是否包含某个元素,返回
boolean 值
方法:
/ 声明一个 Set let s = new Set() let s2 = new Set(['大事儿','小事儿','好事儿','坏事儿','小事儿']) console.log(s, Object.prototype.toString.call(s)) // Set(0) "[object Set]" console.log(s instanceof Object) // true console.log([...s2],typeof [...s2]) // (4) ["大事儿", "小事儿", "好事儿", "坏事儿"] "object" // 自动去重 console.log(s2) // Set(4) {"大事儿", "小事儿", "好事儿", "坏事儿"} // 元素个数 // console.log(s2.size) // 4 // 添加新的元素 // s2.add('喜事儿') // console.log(s2) // Set(5) {"大事儿", "小事儿", "好事儿", "坏事儿", "喜事儿"} // 删除元素 // s2.delete('坏事儿') // console.log(s2) // Set(3) {"大事儿", "小事儿", "好事儿"} // 检测 // console.log(s2.has('好事儿')) // true // console.log(s2.has('糟心事')) // false // console.log(s2) // 清空 // s2.clear() // console.log(s2) // Set(0) {} for(let v of s2) { console.log(v) // 遍历 }
应用:
let arr = [1,2,3,4,5,4,3,2,1] // 1.数组去重 let result1 = [...new Set(arr)] // 因为 Set 集合实现了 iterator 接口,所以可以直接使用拓展运算符来使用遍历 console.log(result1) // (5) [1, 2, 3, 4, 5] // 2.交集 let arr2 = [4,5,6,5,6] let s2 = new Set(arr2) console.log(s2) // Set(3) {4, 5, 6} console.log([...new Set(arr2)],Object.prototype.toString.call([...new Set(arr2)])) // (3) [4, 5, 6] "[object Array]" let result2 = [...new Set(arr)].filter(item => s2.has(item)) console.log(result2) // (2) [4, 5] // 3.并集 let union = [...new Set([...arr, ...arr2])] console.log(union) // (6) [1, 2, 3, 4, 5, 6] // 4.差集 let diff = [...new Set(arr)].filter(item => !s2.has(item)) console.log(diff) // (3) [1, 2, 3]