第九章(集合)

来源:互联网 发布:ubuntu 14.04安装qq 编辑:程序博客网 时间:2024/06/13 15:10

1,集合中的元素是无序的;

2,用来保存独一无二的元素,比如一段文本中用到的单词,先检索有没有在数组中出现再确定是否往数组中添加。

function Set(){this.dataStore=[];//数组this.add=add;//增加this.remove=remove;//删除//this.contains=contains;this.size=size;//大小this.union=union;//并集this.intersect=intersect;//交集this.subset=subset;//子集this.difference=difference;//补集this.show=show;//显示集合this.contanins=contanins;}function add(data){if(this.dataStore.indexOf(data)>=0){return false;}else{this.dataStore.push(data);return true;}}function remove(data){var pos=this.dataStore.indexOf(data);if(pos>-1){this.dataStore.splice(pos,1);return true;}else{return false;}}function show(){return this.dataStore;}function contanins(data){if(this.dataStore.indexOf(data)>-1){return true;}else{return false;}}//并集function union(set){var tempSet= new Set();for(var i=0;i<this.dataStore.length;++i){tempSet.add(this.dataStore[i]);}for(var i=0;i<set.dataStore.length;++i){if(!tempSet.contanins(set.dataStore[i])){tempSet.dataStore.push(set.dataStore[i]);}}return tempSet;}//交集function intersect(set){var tempSet=new Set();for(var i=0;i<this.dataStore.length;i++){if(set.contanins(this.dataStore[i])){tempSet.add(this.dataStore[i]);}}return tempSet;}//子集function subset(set){if(this.size()>set.size()){return false;}else{for(var member in this.dataStore){if(!set.contains(member)){return false;}}return true;}}//大小function size(){return this.dataStore.length;}//补集function difference(set){var tempSet=new Set();for(var i=0;i<this.dataStore.length;++i){if(!set.contanins(this.dataStore[i])){tempSet.add(this.dataStore[i]);}}return tempSet;}//主程序var seta=new Set();seta.add("zhangsan");seta.add("lisi");seta.add("wangwu");seta.add("maliu");var setb=new Set();setb.add("maliu");setb.add("qiqi");setb.add("basi");console.log("seta:"+seta.show());console.log("setb:"+setb.show());console.log("seta&setb:"+seta.union(setb).show());console.log("seta与setb的交集:"+seta.intersect(setb).show());console.log("seta是setb的子集吗?:"+seta.subset(setb));console.log("seta在setb的补集:"+seta.difference(setb).show());


原创粉丝点击