ES6 && Set 和 WeakSet
1. Set
新的資料結構,成員是唯一的,沒有重複的值。
Set
函式可以接受一個數組作為引數
// 例一 const set = new Set([1, 2, 3, 4, 4]); [...set] // [1, 2, 3, 4] // 例二 const items = new Set([1, 2, 3, 4, 5, 5, 5, 5]); items.size // 5
陣列去重
// 去除陣列的重複成員 [...new Set(array)]
字串去重
[...new Set('ababbc')].join('') // "abc"
Set 例項的方法分為兩大類:操作方法(用於操作資料)和遍歷方法(用於遍歷成員)
- 操作方法:
- add(value):新增某個值,返回 Set 結構本身。
- delete(value):刪除某個值,返回一個布林值,表示刪除是否成功。
- has(value):返回一個布林值,表示該值是否為Set的成員。
- clear():清除所有成員,沒有返回值。
s.add(1).add(2).add(2); // 注意2被加入了兩次 s.size // 2 s.has(1) // true s.has(2) // true s.has(3) // false s.delete(2); s.has(2) // false
- 遍歷操作
- keys():返回鍵名的遍歷器
- values():返回鍵值的遍歷器
- entries():返回鍵值對的遍歷器
- forEach():使用回撥函式遍歷每個成員
用 Set 實現並集、交集和差集
let a = new Set([1, 2, 3]); let b = new Set([4, 3, 2]); // 並集 let union = new Set([...a, ...b]); // Set {1, 2, 3, 4} // 交集 let intersect = new Set([...a].filter(x => b.has(x))); // set {2, 3} // 差集 let difference = new Set([...a].filter(x => !b.has(x)));
2. WeakSet
成員只能接受物件
WeakSet 的一個用處,是儲存 DOM 節點,而不用擔心這些節點從文件移除時,會引發記憶體洩漏。
const foos = new WeakSet() class Foo { constructor() { foos.add(this) } method () { if (!foos.has(this)) { throw new TypeError('Foo.prototype.method 只能在Foo的例項上呼叫!'); } } }
上面程式碼保證了Foo的例項方法,只能在Foo的例項上呼叫。這裡使用 WeakSet 的好處是,foos對例項的引用,不會被計入記憶體回收機制,所以刪除例項的時候,不用考慮foos,也不會出現記憶體洩漏。