数据结构Set学习,去重,交集,缓存数据

Set 是一种无序且不重复的数据结构,它可以用来存储一组具有唯一性的数据。在 JavaScript 中,Set 是一种内置的数据类型,我们可以使用 Set() 构造函数来创建 Set 对象,然后使用其提供的方法来操作 Set

常用方法:

  1. 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}
     
    
  2. 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
     
    
  3. 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}
    
  4. 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 '这个没有,给添加上';
  }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值