集合set()类(对象【值,值】)

集合用对象来存储:对象对于属性与方法的存储具有唯一性,不存在两个重复的值。

function set(){
var  items={  };

}

***判断集合中是否有这个值:

this.has=function(value){
return value in items;

}或者

this.has=function(value){

return  items.hasOwnProperty(value);

}

***向集合添加值:

this.add=function(value){
if(!this.has(value)){ //如果集合中没有这个值的话

items[value]=value;

return true;

}return false;

}

***删除集合中指定的值:

this.remove=function(value){

if(this.has(value)){
delete items.value; 在对象中,可以使用delete删除属性;

}}

***移除集合中所有的值:

this.clear=function(){

items={ };

}

***返回集合值的长度:

this.size=function(){
return object.keys(items).length;

}

object.keys()方法以数组的方式返回对象的属性的集合;数组中属性名的排列顺序和使用 for...in 循环遍历该对象时返回的顺序一致。

方法二:

this.size=function(){

var count=0;
for(var pop in items){

if(items.hasownproperty(pop))

count++;

}

return count;

}

}

***以数组方式返回集合中的属性

this.value=function(){
return object.keys(items);

}

操作集合:

***并集(a和b集合合在一起)

this.union=function(otherset){  //otherset是要被合并到set的其他集合

var value=this.values();

var addset=new set();

for(var i=0;i<value.length;i++){
addset.add(value[i]);

}

var value=otherset.values();

for(var i=0;i<value.length;i++){
addset.add(value[i]);

}

return addset;

}

***交集:

this.intersection=function(otherset){
var  unionset=new set();

var value=otherset.values();

for(var i=0;i<value.length;i++){

if(set.has(value[i]) ){  //第五行

unionset.add(value[i])

}}

return unionset;

}

***差集:

this.difference=交集中的第五行取反:if(  !set.has(value[i])  )

***子集:a全部在B中:

this.subset = function(otherSet){ 
this.subset=function(){
    if (this.size() > otherSet.size())

{return false;  

  } else {      

  var values = this.values();        

for (var i=0; i<values.length; i++){

          if (!otherSet.has(values[i])){           

    return false;  }         }    

    return true;  } };

猜你喜欢

转载自blog.csdn.net/kalinux/article/details/81951631