js 往对象集合加元素

JavaScript011

js 往对象集合加元素,第1张

有时候项目需要往json加入一些参数。

1.如果是数组Array就可以直接用a.push(xxx) 的方式加入

2.如果是一个集合,就是对象的话[{ aa:11,bb:22},{ aa:11,bb:22}],那么可以用遍历(点xx)的方式添加

这样出来结果就是

<!--封装集合类-->

//我们的集合里面不允许有重复的元素

    function Set(){

//    属性

        this.items={}

//    add方法

        Set.prototype.add=value=>{

//判断当前集合是否包含了该元素

            if (this.has(value))return false

            //将元素添加到集合中

            this.items[value]=value//集合中,键为value,值为value

            return true

        }

//        has方法--判断集合中是否有某一个元素!

        Set.prototype.has=(value)=>{

return this.items.hasOwnProperty(value)

}

//        remove方法

        Set.prototype.remove=(value)=>{

//  1.判断集合中是否包含该元素

            if (!this.has(value))return false

        //  2.包含则删除集合中的属性,delete是js中的属性

            delete this.items[value]

return true

        }

//        clear方法

        Set.prototype.clear=()=>{

this.items={}

}

//        size方法

        Set.prototype.size=()=>{

return Object.keys(this.items).length

        }

//        获取集合中所有的值

        Set.prototype.values=()=>{

return Object.keys(this.items)

}

}