集合中的交集和差異

集合中沒有用於交集和差異的內建方法,但你仍然可以實現該方法,但將它們轉換為陣列,過濾並轉換回集合:

var set1 = new Set([1, 2, 3, 4]),
    set2 = new Set([3, 4, 5, 6]);

const intersection = new Set(Array.from(set1).filter(x => set2.has(x)));//Set {3, 4}
const difference = new Set(Array.from(set1).filter(x => !set2.has(x))); //Set {1, 2}