前言

集合就是数学中的集合概念, 只不过用到了编程语言中. 也就是Set类

概念: 由一组无序且唯一的项组成.

正文

下面就让我们来实现Set类

class MySet{

  items = {} //存放数据的对象, 这次使用的是对象来存放, 而不是数组, 主要是对象更方便

  //集合是否存放了这个数据
  has(value){
    return this.items.hasOwnProperty(value)
  }

  //在集合中添加一个数据
  add(value){
    if(!this.has(value)){
      this.items.
    }
  }

  //移除集合中某个元素
  remove(value){
    if(!this.has(value)){
      delete this.items[value]
      return true
    }
    return false
  }

  //移除集合中所有元素
  clear(){
    this.items = {}
  }

  //获得集合中元素个数
  size(){
    return Object.keys(this.items).length
  }

  //获得集合中所有元素
  values(){
    return Object.keys(this.items)
  }

  //下面实现集合的 并集 交集 合集 子集

  //并集
  union(otherSet){
    const unionSet = new MySet()
    const selfSetValues = this.values()
    for(let selfVal of selfSetValues){
      unionSet.add(selfVal)
    }
    const otherSetValues = otherSet.values()
    for(let otherVal of otherSetValues){
      unionSet.add(otherVal)
    }
    return unionSet
  }

  //交集
  intersection(otherSet){
    const intersectionSet = new MySet()
    const selfSetValues = this.values()
    for(let selfVal of selfSetValues){
      if(otherSet.has(selfVal)){
        intersectionSet.add(selfVal)
      }
    }
    return intersectionSet
  }

  //差集(本集合和另一个集合不同的元素)
  difference(otherSet){
    const differenceSet = new MySet()
    const selfSetValues = this.values()
    for(let selfVal of selfSetValues){
      if(!otherSet.has(selfVal)){
        differenceSet.add(selfVal)
      }
    }
    return differenceSet
  }

  //子集(判断本集合是否是另一个集合的子集)
  isSub(otherSet){
    if(this.size()>otherSet.size()){
      return false
    }
    const selfSetValues = this.values()
    for(let selfVal of selfSetValues){
      if(!otherSet.has(selfVal)){
        return false
      }
    }
    return true
  }
  
}

注意: ① in关键字遍历items对象时, 会把items继承的类属性也找出来, 而hasOwnProperty方法of关键字 只会遍历item对象本身的属性, 所以我没用in关键字

结尾

今天我们实现了集合这种数据结构, 大家对集合这种数据结构也有了更深刻的认识.

THE END
开启精彩搜索

历史搜索

用户名或邮箱
密码
用户名
密码
重复密码
邮箱
注册
找回密码
注册 登录
邮箱
邮箱验证码
发送验证码
59秒后可重发
新密码
重复密码
请选择支付方式
余额支付

购买将消耗【10

微信支付
微信扫码支付 0 元
[ 04分50秒 ]
请使用微信扫一扫
扫描二维码支付
支付宝支付
支付宝扫码支付 0 元
[ 04分50秒 ]
请使用支付宝扫一扫
扫描二维码支付
已完成支付
未完成支付

请输入验证码

点击验证码可以刷新

你确认吗?

确认

2024年10月1日

新增

新增