集合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;  } };

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值