Set是什么?它的方法有哪些?它在实例开发中有什么作用?
让我为大家介绍一下吧!
ES6提供了新的数据结构 Set(集合) 。它类似于数组,但成员的值是唯一的,常用于数组去重。
创建方法:
let s = new Set()console.log(s)
它属于什么类型?
console.log(typeof s) //object
我们通常在set中写入数组
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])console.log(s)
由此可见,set 可以自动帮我们去重
Set 对象的几个常用方法和属性
1.size
可以获取元素的个数
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])console.log(s.size) //4
2.add( )
向 Set 添加新元素
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])s.add("四大名著")console.log(s)
3.delete( )
删除由其值指定的元素
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])s.add("四大名著")s.delete("四大名著")console.log(s)
4.has( )
如果值存在则返回 true,否则false
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])console.log(s.has("西游记")) //trueconsole.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)}
7.keys( )
let s = new Set(["西游记","三国演义","水浒传","红楼梦","西游记"])console.log(s.keys())
8.forEach( )
为每个元素调用回调
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);
感谢大家的阅读,如有不对的地方,可以向我指出,感谢大家!