Set的基本使用
ES6 提供了新的數據結構 Set。它類似於數組,但是成員的值都是唯一的,沒有重復的值。
返回的結果是一個set集合,和數組對象都不一樣,是一個新的數據集合
設置初始值的方法有兩種,第一中是通過add()方法進行設置的,第二種就是初始化的時候內部設置數組
let set = new Set(["a","b","c"]); console.log(set);
注意:如果我們想要使用初始化復制的狀態,賦值必須是數組,不可以是對象等等
set內部的賦值不能有重復
let set = new Set(); // 插入數據 set.add("a"); set.add("a"); set.add("a"); set.add("b"); set.add("b"); set.add("b"); set.add("c"); set.add("c"); set.add("c"); console.log(set);
也可以連續打點使用
Set的方法
插入值使用的是add方法
向Set加入值的時候,不會發生類型轉換,所以1和"1"是兩個不同的值。
刪除值使用的是delete方法
內部想刪除哪個數據就填哪個數據
let set = new Set([1,2,3,4,5]); set.delete(3) console.log(set);
檢測內部是否有該值
let set = new Set([1,2,3,4,5]); console.log(set.has(3));
求集合的長度
判斷長度不是length,是size
清空集合內部所有的數據
let arr = new Set([1,2,3,4,5]); arr.clear() console.log(arr);
set的循環
map和set是可以使用for..of進行遍歷,是因為map和set都是iterator接口機制
let arr = new Set([1,2,3,4,5]); for(let item of arr) { console.log(item); }
可以使用keys和values進行變量來看一下set集合key和value分別是什么
let arr = new Set([1,2,3,4,5]); for(let item of arr.keys()) { console.log(item); } for(let item of arr.values()) { console.log(item); }
set集合的key和value是相同的
set也可以用forEach去遍歷
let arr = new Set([1,2,3,4,5]); arr.forEach((item,index)=>{ console.log(item,index); })
set也可以使用entries方法去遍歷
let arr = new Set([1,2,3,4,5]); for(let item of arr.entries()) { console.log(item); }
Set轉換為數組
由於set不能使用數組的方法,雖然forEach可以用,但是僅僅是forEach方法,其他是不可以的,比如map、filter
下面的方法是錯誤的,因為map是數組的方法,set不能用
let arr= new Set([1,2,3,4,5]); arr= arr.map((item)=>{ return item * 2 })
如果想操作set中的數據,需要將set轉換為數組
如何轉換?'…'擴展運算符是有iterator接口機制,所以set就可以使用'…'運算符
set轉換為數組
let arr = new Set([1,2,3,4,5]); console.log([...arr]);
可以將set的內部值統一乘以2
let arr = new Set([1,2,3,4,5]); console.log(new Set([...arr].map(item=>item*2)));
先將set通過…運算符轉換為普通數組,然后再用map方法
可以利用set和數組的各自特點做去重,比如數組的去重
let arr = [1,1,1,2,2,2,3,3,3,4,4] let arr2 = [...new Set(arr)]; console.log(arr2);