JavaScript数据结构——集合(Set)

本文介绍了JavaScript中的集合(Set)数据结构,强调了集合中元素的唯一性和无序性。文章详细阐述了集合的基本概念、结构,并列举了包括检查元素存在、添加、移除、清空、获取长度、并集、交集和差集在内的九种常见操作。同时,提供了使用JavaScript对象实现集合结构的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概念和结构

  • 集合里面的元素不能重复
  • 集合里面的元素只有值。
  • 不包含任何元素的集合叫空集。

集合的操作

集合有九种常用操作,分别为

  1. 检查元素是否存在 has(element)
  2. 添加元素 add(element)
  3. 移除元素 remove(element)
  4. 清空集合 clear()
  5. 获取集合长度 size()
  6. 提取集合所有值 values()
  7. 并集 union(otherSet)
  8. 交集 intersection(otherSet)
  9. 差集 difference(otherSet)

JS实现

JS里面的集合结构需要通过对象(object)来实现,因为集合里面的元素只有值,没有键或索引,因此我们可以让对象里面的属性的键值对取相同的值来达到这个效果。

function MySet(){
    
    var set = {};

    //检查元素是否存在
    this.has = function(element){
        return set.hasOwnProperty(element);
    }

    //添加元素
    this.add = function(element){
        if(this.has(element)){
            //元素已经有了
            return false;
        }else{
            //元素没有则添加
            set[element] = element;
            return element;
        }
    }

    //删除元素
    this.remove = function(element){
        if(this.has(element)){
            //元素有了则删除
            delete set[element];
            return true;
        }else{
            //元素没有
            return false;
        }
    }

    //清空集合
    this.clear = function(){
        set = {};
    }

    //获取集合长度
    this.size = function(){
        return Object.keys(set).length;
    }

    //提取集合所有值
    this.values = function(){
        var result = [];
        for(var key in set){
            if(set.hasOwnProperty(key)){
                result.push(set[key]);
            }
        }
        return result;
    }

    //并集
    this.union = function(otherSet){
        var result = new MySet();
        this.values().forEach(element => {
            result.add(element);
        });
        otherSet.values().forEach(element => {
            result.add(element);
        });
        return result;
    }

    //交集
    this.intersection = function(otherSet){
        var result = new MySet();
        this.values().forEach(element => {
            if(otherSet.has(element)){
                result.add(element);
            }
        });
        return result;
    }

    //差集
    this.difference = function(otherSet){
        var result = new MySet();
        this.values().forEach(element => {
            if(!otherSet.has(element)){
                result.add(element);
            }
        });
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值