javascript 集合

//封装集合类
    function Set(){
        //属性
        this.items={}

        //方法
        //add方法
        Set.prototype.add=function(value){
           //判断当前集合中是否已经包含了该元素
           if(this.has(value)){
               return false
           }

           //将元素添加到集合中
           this.items[value]=value
           return true
        }

        //has方法(指定对象自身属性中是否具有指定的属性)
        Set.prototype.has=function(value){
         return this.items.hasOwnProperty(value)
        }

        //remove方法
        Set.prototype.remove=function(value){
            //1.判断该集合中是否包含该元素
            if(!this.has(value)) return false

            //2.将元素从属性中删除
            delete this.items[value]
            return true
        }

        //clear方法
        Set.prototype.clear=function(){
            this.items={}
        }

        //size方法
        Set.prototype.size=function(){
            return Object.keys(this.items).length
        }

        //获取集合中所有的值
        Set.prototype.values=function(){
            return Object.keys(this.items)
        }
    }

    //测试 Set 类
    //1.常见 set 类对象
    var set=new Set()
    
    //2.添加 元素
    alert(set.add('abc'))
    alert(set.add('abc'))
    alert(set.add('cba'))
    alert(set.add('nba'))
    alert(set.add('mba'))

    alert(set.values())

    //3.删除元素
    alert(set.remove('abc'))
    alert(set.remove('abc'))
    alert(set.values())

    //4.has方法
    alert(set.has('abc'))

    //5.获取元素的个数
    alert(set.size())
    set.clear()
    alert(set.size())

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章