当前位置:   article > 正文

js:Set集合的实现_js实现set

js实现set

1.set集合的定义

         集合成员是无序的,是不重复的一组成员。

         开发中可用于去除重复数据

        set集合和map不一样。这里只实现了set集合的方法。

        map是用哈希结构的定义来实现的,本质上也是对数组和链的结合。

        方法就不介绍了,集合的定义数学都是学过的。

2.封装对象 

        此处用对象的方式来实现集合

  1. function Set(){
  2. this.items={}
  3. }

 3.新增值

    默认set的健名是其健值

  1. Set.prototype.add=function(value){
  2. if(this.has(value)){
  3. return false
  4. }
  5. this.items[value]=value
  6. return true
  7. }

 3.删除值

  1. Set.prototype.has=function(value){
  2. return this.items.hasOwnProperty(value)
  3. }
  4. Set.prototype.remove=function(value){
  5. if(!this.has(value)){
  6. return false
  7. }
  8. delete this.items[value]
  9. return true
  10. }

 4.一般方法

  1. Set.prototype.clear=function(){
  2. this.items={}
  3. }
  4. Set.prototype.size=function(){
  5. return Object.keys(this.items).length
  6. }
  7. Set.prototype.values=function(){
  8. return Object.keys(this.items)
  9. }

5.并集 

  1. Set.prototype.union=function(otherSet){
  2. var unionSet=new Set()
  3. var values=this.values()
  4. for(var i=0;i<values.length;i++){
  5. unionSet.add(values[i])
  6. }
  7. values=otherSet.values()
  8. for(var i=0;i<values.length;o++){
  9. unionSet.add(values[i])
  10. }
  11. return unionSet
  12. }

 6.交集

  1. Set.prototype.intersection=function(otherSet){
  2. var intersectionSet=new Set()
  3. var values=this.values()
  4. for(var i=0;i<values.length;i++){
  5. var item=values[i]
  6. if(otherSet.has(item)){
  7. intersectionSet.add(item)
  8. }
  9. }
  10. return intersectionSet
  11. }

7. 补集

  1. Set.prototype.difference=function(otherSet){
  2. var differenceSet=new Set()
  3. var values=this.values()
  4. for(var i=0;i<values.length;i++){
  5. var item=values[i]
  6. if(!otherSet.has(item)){
  7. differenceSet.add(item)
  8. }
  9. }
  10. return differenceSet
  11. }

8.子集 

  1. Set.prototype.subset=function(otherSet){
  2. var values=this.values()
  3. for(var i=0;i<values.length;i++){
  4. var item=values[i]
  5. if(!otherSet.has(item)){
  6. return false
  7. }
  8. }
  9. return true
  10. }

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/763588
推荐阅读
相关标签
  

闽ICP备14008679号