1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>集合</title> 6 </head> 7 <body> 8 <script> 9 function Set(){ 10 this.arr = []; 11 this.add = add; 12 this.remove = remove; 13 this.size = size; 14 this.union = union; //并集 15 this.intersect = intersect; //交集 16 this.subset = subset; //是否是子集 17 this.difference = difference; //补集 18 this.show = show; 19 this.contains = contains; 20 } 21 function contains(data){ 22 return this.arr.indexOf(data)>-1 ? true:false; 23 } 24 function add(data){ 25 if(this.arr.indexOf(data)<0){ 26 this.arr.push(data); 27 return true; 28 }else{ 29 return false; 30 } 31 } 32 33 function remove(data){ 34 var pos = this.arr.indexOf(data); 35 if(pos >-1){ 36 this.arr.splice(pos,1); 37 return true; 38 }else{ 39 return false; 40 } 41 } 42 43 function show(){ 44 return this.arr; 45 } 46 function union(set){ 47 var temp = new Set(); 48 for(var i = 0;i<this.arr.length;i++){ 49 temp.add(this.arr[i]); 50 } 51 for(var i = 0;i<set.arr.length;i++){ 52 if(!temp.contains(set.arr[i])){ 53 temp.arr.push(set.arr[i]); 54 } 55 } 56 return temp; 57 } 58 59 function intersect(set){ 60 var temp = new Set(); 61 for(var i=0;i<this.arr.length;i++){ 62 if(set.contains(this.arr[i])){ 63 temp.add(this.arr[i]); 64 } 65 } 66 return temp; 67 } 68 69 function size(){ 70 return this.arr.length; 71 } 72 function subset(set){ 73 if(this.size() > set.size()){ 74 return false; 75 }else{ 76 for(var member in this.arr){ 77 if(!set.contains(member)){ 78 return false; 79 } 80 } 81 } 82 return true; 83 } 84 85 function difference(set){ 86 var temp = new Set(); 87 for(var i= 0;i<this.arr.length;i++){ 88 if(!set.contains(this.arr[i])){ 89 temp.add(this.arr[i]); 90 } 91 } 92 return temp; 93 } 94 95 // 96 var obj = new Set(); 97 obj.add("zhangsan"); 98 obj.add("lisi"); 99 obj.add("wangwu"); 100 obj.add("zhaoliu"); 101 102 console.log(obj.show()); 103 obj.remove("wangwu"); 104 console.log(obj.show()); 105 106 var obj1 = new Set(); 107 obj1.add("javascript"); 108 obj1.add("zhangsan"); 109 110 console.log(obj.union(obj1)); 111 console.log(obj.intersect(obj1)); 112 console.log(obj.subset(obj1)); 113 console.log(obj.difference(obj1)); 114 </script> 115 </body> 116 </html>