簡介
最近在看阮一峰的es6,學(xué)習(xí)到了set函數(shù)铝噩。這可是處理數(shù)組的黑魔法,很多問題很好解決窿克。
ES6 提供了新的數(shù)據(jù)結(jié)構(gòu) Set骏庸。它類似于數(shù)組,但是成員的值都是唯一的,沒有重復(fù)的值。
Set 本身是一個構(gòu)造函數(shù)耍休,用來生成 Set 數(shù)據(jù)結(jié)構(gòu)灶泵。
const s = new Set();
[2, 3, 5, 4, 5, 2, 2].forEach(x => s.add(x));
for (let i of s) {
console.log(i);
}
根據(jù)Set這個特性,我們很方便實現(xiàn)數(shù)組去重补箍。
[...new Set([1,1,5,3])];
//[1,5,3];
而且改执,數(shù)組的map和filter方法也可以用于 Set 了啸蜜。
let set = new Set([1, 2, 3]);
set = new Set([...set].map(x => x * 2));
// 返回Set結(jié)構(gòu):{2, 4, 6}
let set = new Set([1, 2, 3, 4, 5]);
set = new Set([...set].filter(x => (x % 2) == 0));
// 返回Set結(jié)構(gòu):{2, 4}
因此使用 Set 可以很容易地實現(xiàn)并集(Union)、交集(Intersect)和差集(Difference)辈挂。
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)));
// Set {1}