蓝桥杯web工作协调
在 JavaScript 里,Set
是一种内置对象,可存储任何类型的唯一值,无论是原始值还是对象引用。下面是 Set
集合常用方法的介绍:
1. 创建 Set
可以使用 new Set()
来创建一个空的 Set
,或者传入一个可迭代对象来初始化 Set
。
// 创建一个空的 Set
const emptySet = new Set();
// 使用数组初始化 Set
const setFromArray = new Set([1, 2, 3, 4, 5]);
2. 添加元素
可以使用 add()
方法往 Set
里添加新元素。
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
console.log(mySet); // 输出: Set(3) { 1, 2, 3 }
3. 检查元素是否存在
使用 has()
方法来检查 Set
中是否存在某个元素。
const mySet = new Set([1, 2, 3]);
console.log(mySet.has(2)); // 输出: true
console.log(mySet.has(4)); // 输出: false
4. 删除元素
使用 delete()
方法从 Set
中删除指定元素。
const mySet = new Set([1, 2, 3]);
mySet.delete(2);
console.log(mySet); // 输出: Set(2) { 1, 3 }
5. 获取 Set
的大小
使用 size
属性来获取 Set
中元素的数量。
const mySet = new Set([1, 2, 3]);
console.log(mySet.size); // 输出: 3
6. 清空 Set
使用 clear()
方法移除 Set
中的所有元素。
const mySet = new Set([1, 2, 3]);
mySet.clear();
console.log(mySet); // 输出: Set(0) {}
7. 遍历 Set
可以使用 forEach()
方法或者 for...of
循环来遍历 Set
中的元素。
const mySet = new Set([1, 2, 3]);
// 使用 forEach 方法
mySet.forEach((value) => {
console.log(value);
});
// 使用 for...of 循环
for (const value of mySet) {
console.log(value);
}
8. 将 Set
转换为数组
可以使用扩展运算符 ...
或者 Array.from()
方法将 Set
转换为数组。
const mySet = new Set([1, 2, 3]);
const arrayFromSet = [...mySet];
const anotherArray = Array.from(mySet);
console.log(arrayFromSet); // 输出: [1, 2, 3]
console.log(anotherArray); // 输出: [1, 2, 3]
这些方法能让你方便地操作和管理 Set
集合中的元素。
解题
class XSet extends Set {
/**
* 与一个或多个集合的并集
* @param sets 元素类型为 XSet 的数组
* @returns {XSet} 返回并集集合,类型为 XSet
*/
union(...sets) {
return XSet.union(this, ...sets);
}
/**
* 与一个或多个集合的交集
* @param sets 元素类型为 XSet 的数组
* @returns {XSet} 返回交集集合,类型为 XSet
*/
intersection(...sets) {
return XSet.intersection(this, ...sets);
}
/**
* 与一个集合的差异
* @param set 类型为 XSet 的集合
* @returns {XSet} 返回差集集合,类型为 XSet
*/
difference(set) {
return XSet.difference(this, set);
}
/**
* 返回两个集合的差集 a-b
* @param a 类型为 XSet 的集合
* @param b 类型为 XSet 的集合
* @returns {XSet} 返回差集集合,类型为 XSet
*/
static difference(a, b) {
const result = new XSet();
for (const element of a) {
if (!b.has(element)) {
result.add(element);
}
}
return result;
}
/**
* 返回两个或多个集合的交集
* @param a 类型为 XSet 的集合
* @param bSets 元素类型为 XSet 的数组
* @returns {XSet} 返回交集集合,类型为 XSet
*/
static intersection(a, ...bSets) {
const result = new XSet();
for (const element of a) {
let isInAllSets = true;
for (const set of bSets) {
if (!set.has(element)) {
isInAllSets = false;
break;
}
}
if (isInAllSets) {
result.add(element);
}
}
return result;
}
/**
* 返回两个或多个集合的并集
* @param a 类型为 XSet 的集合
* @param bSets 元素类型为 XSet 的数组
* @returns {XSet} 返回并集集合,类型为 XSet
*/
static union(a, ...bSets) {
const result = new XSet(a);
for (const set of bSets) {
for (const element of set) {
result.add(element);
}
}
return result;
}
}
// 以下代码为检测需要,请勿删除
try {
module.exports = XSet;
} catch { }