<script type="text/javascript"> //如何判断一个数组是否存在某一元素 //var arr = [1,2,3,5]; //var arr = {a:1,b:2,c:3}; function Set(data){ this.constructor = set; this.dataStore = Object.prototype.toString.apply(data) == ‘[object Array]‘ ? data : []; this.in_array = in_array; this.size = size; this.add = add; this.remove = remove; this.show = show; this.union = union; this.intersect = intersect; //求两个集合的交集 this.is_subset = is_subset; //判断一个集合是否是该集合的子集 this.diff = diff; } //判断数组中是否存在某个元素 function in_array(element){ var position = this.dataStore.indexOf(element); return position < 0 ? false : position; } function add(element){ if(!this.in_array(element,this.dataStore)){ this.dataStore.push(element); return true; }else{ return false; } } function remove(element){ var position = this.in_array(element,this.dataStore); if(position){ this.dataStore.splice(position,1); return true; }else{ return false; } } //求两个集合的并集 function union(data){ var result = this.dataStore.slice(); //js默认为引用传递 var temp = new Set(data); temp.dataStore = data; for(var i=0;i<temp.size();i++){ if(this.in_array(temp.dataStore[i],this.dataStore) === false){ result.push(temp.dataStore[i]); } } return result.sort(); } //求两个集合的交集 function intersect(data){ var result = []; var all = this.union(data); var temp = new Set(data); for(var i=0;i<all.length;i++){ if(this.in_array(all[i],this.dataStore) !== false && temp.in_array(all[i],temp.dataStore) !== false){ result.push(all[i]); } } return result; } //求集合1与集合2的差集 function diff(data){ var result = []; //结果集 var all = this.union(data); var temp = new Set(data); temp.dataStore = data; for(var i=0;i<all.length;i++){ if(this.in_array(all[i],this.dataStore) !== false && temp.in_array(all[i],temp.dataStore) === false){ result.push(all[i]); } } return result.sort(); } //求集合的补集 function complement(){ } //判断一个集合是否是另一个集合的子集 function is_subset(data){ var temp = new Set(data); for(var i=0;i<temp.size();i++){ if(!this.in_array(temp.dataStore[i],this.dataStore)){ return false; } } return true; } /* function diff(data){ var result = []; //结果集 var all = this.union(data); var temp = new Set(data); temp.dataStore = data; for(var i=0;i<all.length;i++){ if((this.in_array(all[i],this.dataStore) === false && temp.in_array(all[i],temp.dataStore) !== false) || (this.in_array(all[i],this.dataStore) !== false && temp.in_array(all[i],temp.dataStore) === false)){ result.push(all[i]); } } return result.sort(); } */ function size(){ return this.dataStore.length; } function show(){ return this.dataStore; } var arr1 = [0,1,2,3]; var arr2 = [1,2,3]; var set = new Set(arr1); //alert(set.size()); //获取集合有几个元素 //set.remove(5); alert(set.is_subset(arr2)); //alert(set.union(arr2)); //alert(set.show()); </script>
原文:http://www.cnblogs.com/liwuming/p/4488965.html