JS-Set
声明和定义:
<script> //第一种:在执行构造的时候,传递参数 let hd = new Set([1, 2, 3, 4]); console.log(hd); //输出 {1, 2, 3, 4} //第二种,hd.add()添加 let harden = new Set(); harden.add(1); harden.add("1"); //严格类型检测 harden.add(1); //如果值相同,类型相同,不能重复 console.log(harden); //输出 {1, '1'} </script>
Set和数组类型的互相转换:
<script> //Set 类型转换为数组 let s = new Set([1,2,3,4]); console.log(Array.from(s)); console.log([...s]); //把set中大于5的数字剔除掉 let hd = new Set('123456789'); let arr = [...hd].filter(function(item){ return item <5; }) console.log(arr); //数组转换为Set let array = [1,2,3,4,1,2,3,4]; //把数组中重复的值去除 let set = new Set(array); set = [...set]; console.log(set); </script>
Set并集交集差集(太牛了)
<script> let a = new Set([1, 2, 3, 4]); let b = new Set([2, 3, 4, 5]); //并集,不会有重复的,1,2,3,4,5 console.log(new Set([...a,...b])); //a-b 只有1 console.log( new Set( [...a].filter(function(item){ return !b.has(item); }) ) ); //交集,a,b都有的,2,3,4 console.log( new Set( [...a].filter(function (item) { return b.has(item); }) ) ); </script>