示例 1: 设置并集操作
// perform union operation // contain elements of both sets function union(a, b) { let unionSet = new Set(a); for (let i of b) { unionSet.add(i); } return unionSet } // two sets of fruits const setA = new Set(['apple', 'mango', 'orange']); const setB = new Set(['grapes', 'apple', 'banana']); const result = union(setA, setB); console.log(result);
输出
Set {"apple", "mango", "orange", "grapes", "banana"}
集合并集操作将两个集合的元素合二为一。
使用
new Set()
创建一个新集合
unionSet
。
unionSet 变量包含
setA 的所有值。然后,
for...of
循环用于遍历
setB 的所有元素,并使用
将它们添加到 unionSet add()
方法。
该集合不包含重复值。因此,如果集合包含相同的值,则丢弃后一个值。
示例 2: 设置交点操作
// perform intersection operation // elements of set a that are also in set b function intersection(setA, setB) { let intersectionSet = new Set(); for (let i of setB) { if (setA.has(i)) { intersectionSet.add(i); } } return intersectionSet; } // two sets of fruits const setA = new Set(['apple', 'mango', 'orange']); const setB = new Set(['grapes', 'apple', 'banana']); const result = intersection(setA, setB); console.log(result);
输出
Set {"apple"}
集合交集操作表示同时存在于
setA 和
setB 中的元素。
使用
new Set()
创建一个新集合
intersectionSet
。然后,
for...of
循环用于遍历
setB。对于同时存在于
setA 和
setB 中的每个元素,它们都被添加到交集中。
示例 3: 集差运算
// perform difference operation // elements of set a that are not in set b function difference(setA, setB) { let differenceSet = new Set(setA) for (let i of setB) { differenceSet.delete(i) } return differenceSet } // two sets of fruits const setA = new Set(['apple', 'mango', 'orange']); const setB = new Set(['grapes', 'apple', 'banana']); const result = difference(setA, setB); console.log(result);
输出
Set {"mango", "orange"}
集合差操作表示存在于一个集合中而不存在于另一个集合中的元素。
differenceSet 包含
setA 的所有元素。然后,
for...of
循环用于遍历
setB 的所有元素。如果
setB 中存在的元素在
setA 中也可用,则使用
delete()
方法删除该元素。
示例 4: 设置子集操作
// perform subset operation // true if all elements of set b is in set a function subset(setA, setB) { for (let i of setB) { if (!setA.has(i)) { return false } } return true } // two sets of fruits const setA = new Set(['apple', 'mango', 'orange']); const setB = new Set(['apple', 'orange']); const result = subset(setA, setB); console.log(result);
输出
true
如果
setB 的所有元素都在
setA 中,则集合子集操作返回真。
for...of
循环用于遍历
setB 的元素。如果
setB 中存在的任何元素不存在于
setA 中,则返回
false
。