關閉→
當前位置:知科普>IT科技>set集合 - js

set集合 - js

知科普 人氣:7.49K

1、set集合的定義

 集合成員是無序的,是不重複的一組成員。

開發中可用於去除重複數據

set集合和map不一樣。這裏只實現了set集合的方法。

map是用哈希結構的定義來實現的,本質上也是對數組和鏈的結合。

js set集合

2、封裝對象 

        此處用對象的方式來實現集合 function Set(){        this.items={}}

 3、新增值

    默認set的健名是其健值 Set.prototype.add=function(value){            if(this.has(value)){                return false            }             this.items[value]=value            return true        }

4、刪除值

  Set.prototype.has=function(value){            return this.items.hasOwnProperty(value)        }         Set.prototype.remove=function(value){            if(!this.has(value)){                return false            }            delete this.items[value]            return true        }

5.一般方法

 Set.prototype.clear=function(){            this.items={}        }        Set.prototype.size=function(){            return Object.keys(this.items).length        }         Set.prototype.values=function(){            return Object.keys(this.items)        }

6、並集 

 Set.prototype.union=function(otherSet){            var unionSet=new Set()            var values=this.values()            for(var i=0;i<values.length;i++){                unionSet.add(values[i])            }            values=otherSet.values()            for(var i=0;i<values.length;o++){                unionSet.add(values[i])            }            return unionSet        }

 7、交集

Set.prototype.intersection=function(otherSet){            var intersectionSet=new Set()            var values=this.values()            for(var i=0;i<values.length;i++){               var item=values[i]               if(otherSet.has(item)){                   intersectionSet.add(item)               }            }                       return intersectionSet        }

8、補集

  Set.prototype.difference=function(otherSet){            var differenceSet=new Set()            var values=this.values()            for(var i=0;i<values.length;i++){               var item=values[i]               if(!otherSet.has(item)){                differenceSet.add(item)               }            }                       return differenceSet        }

9、子集 

 Set.prototype.subset=function(otherSet){                        var values=this.values()            for(var i=0;i<values.length;i++){               var item=values[i]               if(!otherSet.has(item)){                return false               }            }                       return true        }
TAG標籤:#js #set #