Set ES6 提供了新的数据结构 Set(集合)。它类似于数组,但成员的值都是唯一的,集合实现了 iterator 接口,所以可以使用『扩展运算符』和『for…of…』进 行遍历,集合的属性和方法: 1) size 返回集合的元素个数 2) add 增加一个新元素,返回当前集合 3) delete 删除元素,返回 boolean 值 4) has 检测集合中是否包含某个元素,返回 boolean 值 5) clear 清空集合,返回 undefined
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>集合</title> </head> <body> <script> //声明一个 set let s = new Set(); let s2 = new Set(['大事儿','小事儿','好事儿','坏事儿','小事儿']); //元素个数 console.log(s2.size); //添加新的元素 s2.add('喜事儿'); //删除元素 s2.delete('坏事儿'); //检测 console.log(s2.has('糟心事')); //清空 s2.clear(); console.log(s2); for(let v of s2){ console.log(v); } </script> </body> </html>
示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Set 实践</title> </head> <body> <script> let arr = [1,2,3,4,5,4,3,2,1]; //1. 数组去重 let result = [...new Set(arr)]; console.log(result); //2. 交集 let arr2 = [4,5,6,5,6]; // 先去重,数据少,性能就会高 let result1 = [...new Set(arr)].filter(item => { let s2 = new Set(arr2);// 4 5 6 if(s2.has(item)){ return true; }else{ return false; } }); let result2 = [...new Set(arr)].filter(item => new Set(arr2).has(item)); console.log(result2); //3. 并集 let union = [...new Set([...arr, ...arr2])]; console.log(union); //4. 差集 let diff = [...new Set(arr)].filter(item => !(new Set(arr2).has(item))); console.log(diff); </script> </body> </html>
标签:ES6,Set,console,log,s2,let,new From: https://www.cnblogs.com/anjingdian/p/16908515.html