JS Set集合

JS Set集合

JS Set集合

JavaScript 中,Set 是一种集合数据结构,很像数组,但是和数组不同的是 Set 中的元素是唯一的,不允许重复。Set 相对于数组来说,在处理元素的增加、删除、查找等操作上更为高效。

创建Set集合

你可以通过以下几种方式来创建一个 Set 集合:

  1. 使用 new Set() 构造函数创建一个空的 Set 集合。
let mySet = new Set();
  1. 使用带有初始值的数组来创建一个包含初始值的 Set 集合。
let mySet = new Set([1, 2, 3, 4, 5]);

Set集合的方法

添加元素

使用 add() 方法向 Set 集合中添加新元素,如果添加的元素已经存在,则会被忽略。

let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2); // 重复元素,将被忽略

console.log(mySet); // Set(2) { 1, 2 }

删除元素

使用 delete() 方法可以从 Set 集合中删除指定元素。

let mySet = new Set([1, 2, 3, 4]);
mySet.delete(2);

console.log(mySet); // Set(3) { 1, 3, 4 }

判断元素是否存在

使用 has() 方法来判断 Set 集合中是否包含指定元素。

let mySet = new Set([1, 2, 3, 4]);
console.log(mySet.has(2)); // true
console.log(mySet.has(5)); // false

清空Set集合

使用 clear() 方法来清空整个 Set 集合。

let mySet = new Set([1, 2, 3, 4]);
mySet.clear();

console.log(mySet); // Set(0) {}

获取Set集合的大小

使用 size 属性可以获取 Set 集合中元素的个数。

let mySet = new Set([1, 2, 3, 4]);
console.log(mySet.size); // 4

遍历Set集合

使用 for...of 循环可以遍历 Set 集合中的所有元素。

let mySet = new Set([1, 2, 3, 4]);

for (let item of mySet) {
    console.log(item);
}

将Set集合转换为数组

使用 Array.from() 方法可以将 Set 集合转换为数组。

let mySet = new Set([1, 2, 3, 4]);
let myArray = Array.from(mySet);

console.log(myArray); // [1, 2, 3, 4]

Set集合的应用场景

Set 集合在实际开发中有很多应用场景,比如:

  1. 去重数组中的重复元素。
let arr = [1, 2, 3, 2, 1];
let uniqueArr = Array.from(new Set(arr));

console.log(uniqueArr); // [1, 2, 3]
  1. 判断一个数组中是否包含重复元素。
function hasDuplicates(arr) {
    return arr.length !== new Set(arr).size;
}

console.log(hasDuplicates([1, 2, 3, 2])); // true
  1. 求两个数组的交集、并集或差集。
let set1 = new Set([1, 2, 3]);
let set2 = new Set([2, 3, 4]);

// 求交集
let intersection = new Set([...set1].filter(x => set2.has(x)));

// 求并集
let union = new Set([...set1, ...set2]);

// 求差集
let difference = new Set([...set1].filter(x => !set2.has(x)));

console.log(intersection); // Set(2) { 2, 3 }
console.log(union); // Set(4) { 1, 2, 3, 4 }
console.log(difference); // Set(1) { 1 }

总结

在本文中,我们介绍了 JavaScript 中的 Set 集合,包括如何创建 Set 集合、常用的方法以及应用场景。Set 集合是一个非常实用的数据结构,能够帮助我们更高效地处理数据。在日常开发中,我们可以根据具体需求灵活运用 Set 集合,提高代码的质量和效率。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程