JavaScript 说明不同集合操作的程序

要理解此示例,您应了解以下 JavaScript 编程 主题


示例 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` 的所有元素,并使用 `add()` 方法将它们添加到 `unionSet` 中。

集合不包含重复值。因此,如果集合包含相同的值,后面的值将被丢弃。


示例 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` 中,则集合子集运算返回 `true`。

使用 `for...of` 循环遍历 `setB` 的元素。如果 `setB` 中存在的任何元素不存在于 `setA` 中,则返回 `false`。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战