💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[Set](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Set "Set 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用。") ES6提供了新的数据结构Set (集合) 。它类似于数组,但成员的**值都是唯一**的,集合实现了iterator接口,所以可以使用 扩展运算符』和(ftor...o....遍历, 集合的属性和方法: 1) size 返回集合的元素个数 2) add 增加一个新元素,返回当前集合 3) delete 删除元素,返回boolean值 4) has 检测集合中是否包含某个元素,返回boolean值 ``` let s=new Set(); console.log(typeof s);//object let s2=new Set([1,2,3,4,5,5]) console.log(s2);//[1, 2, 3, 4, 5] s2.add(6); console.log(s2);//[1, 2, 3, 4, 5,6] s2.delete(6);//[1, 2, 3, 4, 5] s2.has(6)//false for (let v of s2) { console.log(v);//1 2 3 4 5 } s2.clear() console.log(s2);//[] ``` ``` //数组去重 let arr=[1,2,3,4,5,4,3,2,1]; let newArr=[...new Set(arr)]; console.log(newArr)//[1, 2, 3, 4, 5] //交集(共有) let arr1=[1,2,3,4,5,4,3,2,1]; let arr2=[4,5,6,5,6]; let newArr1=[...new Set(arr1)].filter(function(item){ let s2=new Set(arr2); if(s2.has(item)){ return true; }else{ return false; } }); //简写 //let newArr1=[...new Set(arr1)].filter(item=>new Set(arr2).has(item)); console.log(newArr1)//[4, 5] //并集 let arr3=[1,2,3,4,5,4,3,2,1]; let arr4=[4,5,6,5,6]; let union=[...new Set(arr3), ...new Set(arr4)]; console.log(union);//[1, 2, 3, 4, 5, 4, 5, 6] //差集(只有他有) let arr5=[1,2,3,4,5,4,3,2,1]; let arr6=[4,5,6,5,6]; let diff1=[...new Set(arr5)].filter(item=>!(new Set(arr6).has(item))); console.log(diff1);//[1, 2, 3] let diff2=[...new Set(arr6)].filter(item=>!(new Set(arr5).has(item))); console.log(diff2);//[6] ```