返回
ES6中的Set集合:揭秘键值对的独特魅力
前端
2023-12-10 22:31:07
1. Set集合简介
Set集合是ES6中新引入的数据结构,它允许我们存储唯一值,并以插入顺序对其进行迭代。Set集合中的元素不会重复,这意味着每个元素只出现一次。Set集合是无序的,这意味着元素的顺序不是固定的。
2. Set集合的创建
我们可以使用new Set()来创建一个Set集合,也可以通过Set()函数来创建一个Set集合,但是new Set()更加常用。
// 使用new Set()创建Set集合
const set1 = new Set();
// 使用Set()函数创建Set集合
const set2 = Set();
3. Set集合的添加元素
我们可以使用add()方法向Set集合中添加元素。
// 向Set集合中添加元素
set1.add(1);
set1.add(2);
set1.add(3);
4. Set集合的删除元素
我们可以使用delete()方法从Set集合中删除元素。
// 从Set集合中删除元素
set1.delete(2);
5. Set集合的查找元素
我们可以使用has()方法来检查Set集合中是否包含某个元素。
// 检查Set集合中是否包含某个元素
set1.has(1); // true
set1.has(2); // false
6. Set集合的遍历
我们可以使用forEach()方法来遍历Set集合中的元素。
// 遍历Set集合中的元素
set1.forEach((value, key) => {
console.log(key, value);
});
7. Set集合的应用
Set集合在实际开发中有很多应用场景,例如:
- 去除数组中的重复元素
const array = [1, 2, 3, 1, 2, 3];
const set = new Set(array);
const uniqueArray = [...set];
console.log(uniqueArray); // [1, 2, 3]
- 检查元素是否存在
const set = new Set([1, 2, 3]);
console.log(set.has(2)); // true
console.log(set.has(4)); // false
- 交集、并集和差集
const set1 = new Set([1, 2, 3]);
const set2 = new Set([3, 4, 5]);
// 交集
const intersection = new Set([...set1].filter(x => set2.has(x)));
console.log(intersection); // Set { 3 }
// 并集
const union = new Set([...set1, ...set2]);
console.log(union); // Set { 1, 2, 3, 4, 5 }
// 差集
const difference = new Set([...set1].filter(x => !set2.has(x)));
console.log(difference); // Set { 1, 2 }
8. 总结
Set集合是ES6中新引入的数据结构,它允许我们存储唯一值,并以插入顺序对其进行迭代。Set集合在实际开发中有许多应用场景,例如去除数组中的重复元素、检查元素是否存在、交集、并集和差集等。