Set是什么?它的方法有哪些?它在实例开发中有什么作用?
让我为大家介绍一下吧!
ES6提供了新的数据结构 Set(集合) 。它类似于数组,但成员的值是唯一的。
创建方法:
let s = new Set()
console.log(s)
console.log(typeof s) //object
我们通常在set中写入数组
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])
console.log(s)
1.size
可以获取元素的个数
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])
console.log(s.size) //4
2.add( )
向 Set 添加新元素
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])
s.add("四大名著")
console.log(s)
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])
s.add("四大名著")
s.delete("四大名著")
console.log(s)
4.has( )
如果值存在则返回 true,否则false
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])
console.log(s.has("西游记")) //true
console.log(s.has("四大名著")) //false
5.clear( )
清空
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])
s.clear()
console.log(s)
6.我们可以使用for…of遍历
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])
for(let v of s) {
console.log(v)
}
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])
console.log(s.keys())
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])
s.forEach(item=>{
console.log(item)
})
1.数组去重
let arr = [1, 2, 3, 3, 2, 1, 4, 5, 1]
let result = [...new Set(arr)]
console.log(result)
2.交集
let result = [...new Set(arr1)].filter(item=>new Set(arr2).has(item)
// {
// // 把arr2也变成一个集合
// let s2 = new Set(arr2)
// // 判断arr2里是否有arr1里的元素
// if(s2.has(item)){
// return true
// }else {
// return false
// }
// })
)
console.log(result)
3.并集
let arr1 = [1, 2, 3, 3, 2, 1, 4, 5, 1]
let arr2 = [1,2,3,3,2,4]
let result = [...new Set([...arr1,...arr2])]
console.log(result)
4.差集
let arr1 = [1, 2, 3, 3, 2, 1, 4, 5, 1]
let arr2 = [1,2,3,3,2,4]
// 取反
let result = [...new Set(arr1)].filter(item=>!(new Set(arr2).has(item)))
console.log(result);