本文共 2275 字,大约阅读时间需要 7 分钟。
function Set(){ // 属性 this.items = { } // 方法}
// add方法Set.prototype.add = function(value){ // 判断当前集合中是否已经包含了该元素(使用Set的has方法) if(this.has(value)){ return false } // 将元素添加到集合中 this.items[value] = value return true}
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}
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)}
通常包括四种操作:并集、交集、差集、子集
// this: 集合对象A// otherSet: 集合对象BSet.prototype.union = function(otherSet){ // 创建新的集合 var unionSet = new Set() // 将A集合中所有的元素添加到该集合中 var values = this.values() for(var i = 0 ; i < values.length ; i++){ unionSet.add(values[i]) } // 取出B集合中的元素,判断是否需要加到新集合 values = otherSet.values() for(var i = 0 ; i < values.length ; i++){ unionSet.add(values[i]) } return unionSet}
Set.prototype.intersection = function(otherSet){ // 创建新的集合 var intersectionSet = new Set() // 从A集合中取出一个个元素,判断是否同时存在于集合B中,若存在则放入新集合中 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}
Set.prototype.difference = function(otherSet){ // 创建新的集合 var differenceSet = new Set() // 取出A集合一个个元素,判断是否同时存在B集合中,若不存在B中,则添加到新集合中 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}
Set.prototype.subset = function(otherSet){ // 遍历集合A中所有的元素,如果发现集合A中的元素在集合B中不存在,那么false // 如果遍历完了整个A集合,依然没有返回false,则返回true var values = this.values() for(var i = 0; i < values.length ; i++){ var item = values[i] if(!otherSet.has(item)){ return false } } return true}
转载地址:http://lhze.baihongyu.com/