Set 是一种无序且不重复的数据结构,它可以用来存储一组具有唯一性的数据。在 JavaScript 中,Set 是一种内置的数据类型,我们可以使用 Set() 构造函数来创建 Set 对象,然后使用其提供的方法来操作 Set
常用方法:
- Set.add(value):向 Set 中添加一个新元素,如果该元素已经存在于 Set 中,则不会执行任何操作
const set = new Set(); set.add(1); set.add(2); set.add(3); set.add(2); // 添加重复元素 console.log(set); // Set(3) {1, 2, 3}
- Set.has(value):判断 Set 中是否存在某个元素,如果存在则返回 true,否则返回 false。
const set = new Set([1, 2, 3]); console.log(set.has(2)); // true console.log(set.has(4)); // false
- Set.delete(value):从 Set 中删除某个元素,如果删除成功则返回 true,否则返回 false。
const set = new Set([1, 2, 3]); console.log(set.delete(2)); // true console.log(set.delete(4)); // false console.log(set); // Set(2) {1, 3}
- Set.size:获取 Set 中元素的个数。
const set = new Set([1, 2, 3]); console.log(set.size); // 3
示例:去重,交际,并集,数据储存
1.数组去重
const arr1 = [1, 1, 2, 2, 3, 3];
const arr2=[...new Set(arr1)];
console.log(arr2); // [1, 2, 3]
2.可以使用 Set 的交集、并集和差集等方法来判断两个数组是否具有相同的元素。
const arr1 = [1, 2, 3, 4];
const arr2 = [3, 4, 5, 6];
// 交集
const intersect = new Set(arr1.filter(x => arr2.includes(x)));
console.log(intersect); // Set(2) {3, 4}
// 并集
const union = new Set([...arr1, ...arr2]);
console.log(union); // Set(6) {1, 2, 3, 4, 5, 6}
// 差集
const diff = new Set(arr1.filter(x => !arr2.includes(x)));
console.log(diff); // Set(2) {1, 2}
3.数据缓存---以便快速判断某个数据是否已经存在于缓存中。
const abc= new Set();
function cycleData(data) {
if (abc.has(data)) {
return '已经存在了';
} else {
abc.add(data);
return '这个没有,给添加上';
}
}