- add 添加
- remove 删除
- has 是否在集合中
- clear 清空
- size 集合的元素数量
- values 返回一个包含所有值的数组
- union 并集
- intersction 交集
- difference 差集
- subset 子集
js 实现集合
function Set(){ // 元素对象 var items = {}; // 是否存在 this.has = function(value){ return items.hasOwnProperty(value) } // 添加元素 this.add = function(value){ // 如果集合中没有这个元素则添加它 if(!this.has(value)){ items[value] = value; return true; } else{ return false; } } // 删除 this.remove = function(value){ if(this.has(value)){ delete items[value]; return true; }else{ return false; } } // 清除 this.clear = function(){ items = {}; } // 元素个数 this.size = function(){ return Object.keys(items).length; } // 集合的值 this.values = function(){ return Object.keys(items); } // 并集 this.union = function(otherset){ // 实例化一个新的集合 var unionset = new Set(); // 把当前集合合并到新集合中 var values = this.values(); for(let i = 0;i<values.length;i++){ unionset.add(values[i]) } // 要被合并的集合也添加到新集合中 values = otherset.values(); for(let i = 0;i<values.length;i++){ unionset.add(values[i]) } return unionset; } // 交集 this.intersction = function(otherset){ var intersctionSet = new Set(); var values = this.values(); for(let i = 0;i<values.length;i++){ if(otherset.has(values[i])){ intersctionSet.add(values[i]) } } return intersctionSet; } // 差集 this.difference = function(otherset){ var differenceSet = new Set(); var values = this.values(); for(let i= 0;i<values.length;i++){ if(!otherset.has(values[i])){ differenceSet.add([values[i]]) } } return differenceSet; } // 子集 this.subset = function(otherset){ // 如果当前的元素个数大于otherset的元素个数,当前集合就不是其他集合的子集。 if(this.size()>otherset.size())return false; var values = this.values(); for(let i =0;i<values.length;i++){ if(!otherset.has(values[i])) return false; } return true; } } var setA = new Set(); setA.add(1); setA.add(12); setA.add(14); var setB = new Set(); setB.add(1); setB.add(123); setB.add(1333); console.log(setA.intersction(setB).values());