在JavaScript中,虽然没有内置的Set
数据结构(在ES6之前),但ES6引入了Set
对象,它允许你存储唯一的值,无论是原始值或者是对象引用。以下是关于JavaScript中集合(Set
)的一些基础概念:
基础概念:
Set
对象允许你存储唯一的值,无论是原始值或者是对象引用。Set
中的值是唯一的,这意味着你不能有重复的值。Set
对象是可迭代的,这意味着你可以使用for...of
循环来遍历它的元素。相关优势:
Set
会自动去除重复的值,这使得它非常适合用于需要保证元素唯一性的场景。Set
的性能通常优于数组,因为它使用哈希表来存储元素。类型:
Set
主要处理的是值的集合,不支持键值对。应用场景:
Set
。Set
支持一些数学上的集合运算,如并集、交集和差集。示例代码:
let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2); // 重复的值不会被添加
console.log(mySet); // Set {1, 2}
let arr = [1, 2, 2, 3, 4, 4, 5];
let mySet = new Set(arr);
console.log(mySet); // Set {1, 2, 3, 4, 5}
let mySet = new Set([1, 2, 3]);
for (let item of mySet) {
console.log(item);
}
// 输出:
// 1
// 2
// 3
遇到的问题及解决方法:
let mySet = new Set([1, 2, 3]);
let arr = Array.from(mySet);
console.log(arr); // [1, 2, 3]
或者使用扩展运算符:
let arr = [...mySet];
let mySet = new Set([1, 2, 3]);
console.log(mySet.has(2)); // true
console.log(mySet.has(4)); // false
领取专属 10元无门槛券
手把手带您无忧上云