JavaScript Set 和 WeakSet

x33g5p2x  于2022-05-05 转载在 Java  
字(4.3k)|赞(0)|评价(0)|浏览(319)

在本教程中,您将借助示例了解 JavaScript Set 和 WeakSet。
    JavaScript ES6引入了两种新的数据结构,Set 和 WeakSet。
    Set 类似于数组,它允许我们存储多个项,如数字、字符串、对象等。但是,与数组不同的是,Set(集合)不能包含重复值。

创建 JavaScript Set

要创建 Set,您需要使用 new Set() 构造函数。例如,

// create Set
const set1 = new Set(); // an empty set
console.log(set1); // Set {}

// Set with multiple types of value
const set2 = new Set([1, 'hello', {count : true}]);
console.log(set2); // Set {1, "hello", {count: true}}

将重复值传递给 Set 对象时,将排除重复值。

// Set with duplicate values
const set3 = new Set([1, 1, 2, 2]);
console.log(set3); // Set {1, 2}
访问 Set 元素

可以使用 values() 方法访问 Set 元素,并使用 has() 方法检查 Set 中是否有元素。例如,

const set1 = new Set([1, 2, 3]);

// access the elements of a Set
console.log(set1.values()); // Set Iterator [1, 2, 3]

您可以使用 has() 方法检查元素是否在 Set 中。例如,

const set1 = new Set([1, 2, 3]);

// check if an element is in Set
console.log(set1.has(1));
添加新元素

您可以使用 add() 方法将元素添加到 Set。例如,

const set = new Set([1, 2]);
console.log(set.values());

// adding new elements
set.add(3);
console.log(set.values());

// adding duplicate elements
// does not add to Set
set.add(1);
console.log(set.values());

输出

Set Iterator [1, 2]
Set Iterator [1, 2, 3]
Set Iterator [1, 2, 3]
移除元素

您可以使用 clear() 和 delete() 方法从 Set 中删除元素。
    delete() 方法从 Set 中删除特定元素。例如,

const set = new Set([1, 2, 3]);
console.log(set.values()); // Set Iterator [1, 2, 3]

// removing a particular element
set.delete(2);
console.log(set.values()); // Set Iterator [1, 3]

clear() 方法从 Set 中删除所有元素。例如,

const set = new Set([1, 2, 3]);
console.log(set.values()); // Set Iterator [1, 2, 3]

// remove all elements of Set
set.clear();
console.log(set.values()); // Set Iterator []
迭代 Set

您可以使用 for…of 循环或 forEach() 方法遍历 Set 元素。元素按插入顺序访问。例如,

const set = new Set([1, 2, 3]);

// looping through Set
for (let i of set) {
    console.log(i);
}
JavaScript WeakSet

WeakSet 类似于 Set。但是,WeakSet 只能包含对象,而 Set 可以包含任何数据类型,如字符串、数字、对象等。例如,

const weakSet = new WeakSet();
console.log(weakSet); // WeakSet {}

let obj = {
    message: 'Hi',
    sendMessage: true
}

// adding object (element) to WeakSet
weakSet.add(obj);

console.log(weakSet); // WeakSet {{message: "Hi", sendMessage: true}}

当您尝试添加对象之外的其他数据类型时,WeakSet 会抛出一个错误。例如,

// trying to add string to WeakSet
weakSet.add('hello');

// throws error
// TypeError: Attempted to add a non-object key to a WeakSet
console.log(weakSet);
WeakSet 方法

WeakSet 有方法 add()、delete() 和 has()。例如,

const weakSet = new WeakSet();
console.log(weakSet); // WeakSet {}

const obj = {a:1};

// add to a weakSet
weakSet.add(obj);
console.log(weakSet); // WeakSet {{a: 1}}

// check if an element is in Set
console.log(weakSet.has(obj)); // true

// delete elements
weakSet.delete(obj);
console.log(weakSet); // WeakSet {}
WeakSet 不可迭代

与 Set 不同,WeakSet 不可迭代。例如,

const weakSet = new WeakSet({a:1});

// looping through WeakSet
for (let i of weakSet) {

    // TypeError
    console.log(i);
}
数学 Set 运算

在 JavaScript 中,Set 不提供执行数学运算(例如并、交、差等)的内置方法。但是,我们可以创建程序来执行这些运算。

示例:Set 并集操作
// 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
let setA = new Set(['apple', 'mango', 'orange']);
let setB = new Set(['grapes', 'apple', 'banana']);

let result = union(setA, setB);

console.log(result);

输出

Set {"apple", "mango", "orange", "grapes", "banana"}
示例:Set 交集操作
// 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
let setA = new Set(['apple', 'mango', 'orange']);
let setB = new Set(['grapes', 'apple', 'banana']);

let result = intersection(setA, setB);

console.log(result);

输出

Set {"apple"}
示例:Set 差分操作
// 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
let setA = new Set(['apple', 'mango', 'orange']);
let setB = new Set(['grapes', 'apple', 'banana']);

let result = difference(setA, setB);

console.log(result);

输出

Set {"mango", "orange"}
示例:Set 子集操作
// 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
let setA = new Set(['apple', 'mango', 'orange']);
let setB = new Set(['apple', 'orange']);

let result = subset(setA, setB);

console.log(result);

输出

true

JavaScript Set 和 WeakSet 是在ES6中引入的。一些浏览器可能不支持它们的使用。要了解更多信息,请访问JavaScript Set 支持JavaScript WeakSet 支持

上一教程 :JS Map                                          下一教程 :Destructuring Assignment

参考文档

[1] Parewa Labs Pvt. Ltd. (2022, January 1). Getting Started With JavaScript, from Parewa Labs Pvt. Ltd: https://www.programiz.com/javascript/set-weakset

相关文章

最新文章

更多