因为Set中存放的数据都是不会重复的数据,我们在编写JS代码的时候,因此我们可以利用Set来帮助我们更便捷地完成许多的事!
1、JS中Set的定义:
var set = new Set();
2、JS中Set的遍历:
set .forEach(function (element, sameElement, set) { console.log(element); }
3、JS中Set的操作方法:
(1):数组与Set之间的转换:
- 一:数组转Set:
var arr = ["1","2","1","2","3","1"]; var set = new Set(arr); //得到一个新的Set:{"1","2","3"};
- 二:Set转数组:
var arr1= Array.from(set ); //得到一个新的数组:["1","2","3"];
- (2):使用Set给数组去重:
//定义一个新的数组: var arr = ["1","2","1","2","3","1"];
- 方法一:
var arr1 = Array.from(new Set(arr)); //得到一个新的数组:["1","2","3"];
- 方法二:
var arr1 = [...new Set(arr)]; //得到一个新的数组:["1","2","3"];
- (3):求两个Set的并集,交集,差集:
var arr1 = ["1","2","3"]; var arr2 = ["1","2"]; var set1= new Set(arr1); var set2= new Set(arr2); //并集后: var newSet1 = new Set([...set1,...set2]); //得到一个新的Set:{"1","2","3"}; //交集后: var newSet2 = new Set([...set1].filter(x => set2.has(x))); //得到一个新的Set:{"1", "2"}; //差集后: var newSet3 = new Set([...set1].filter(x => !set2.has(x))); //得到一个新的Set:{"3"};
至此,在JS中使用Set的使用方法暂时写到这儿,以后想起来再更新