<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>集合封装</title> </head> <body> <script> function Set(){ this.items={} Set.prototype.add=function(value){ if(this.has(value)){ return false } //判断集合中是否又这个元素 this.items[value]=value return true } Set.prototype.has=function(value){ 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) } 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;i++){ unionSet.add(values[i]) } return unionSet } Set.prototype.intersection=function(otherSet){ var intersection=new Set() var values=this.values() for(var i=0;i<values.length;i++){ unionSet.add(values[i]) if(otherSet.has(item)){ intersection.add(item) } } return intersection } Set.prototype.difference=function(otherSet){ var difference=new Set() for(var i=0;i<values.length;i++){ var item=values[i] if(!otherSet.has(item)){ difference.add(item) } } return difference } } </script> </body> </html>