javascript 集合和字典

网友投稿 311 2022-09-05

javascript 集合和字典

//封装集合类 function Set(){ //属性 this.items={} //方法 //add方法 Set.prototype.add=function(value){ //判断当前集合中是否已经包含了该元素 if(this.has(value)){ return false } //将元素添加到集合中 this.items[value]=value return true } //has方法(指定对象自身属性中是否具有指定的属性) Set.prototype.has=function(value){ return this.items.hasOwnProperty(value) } //remove方法 Set.prototype.remove=function(value){ //1.判断该集合中是否包含该元素 if(!this.has(value)) return false //2.将元素从属性中删除 delete this.items[value] return true } //clear方法 Set.prototype.clear=function(){ this.items={} } //size方法 Set.prototype.size=function(){ return Object.keys(this.items).length } //获取集合中所有的值 Set.prototype.values=function(){ return Object.keys(this.items) } } //测试 Set 类 //1.常见 set 类对象 var set=new Set() //2.添加 元素 alert(set.add('abc')) alert(set.add('abc')) alert(set.add('cba')) alert(set.add('nba')) alert(set.add('mba')) alert(set.values()) //3.删除元素 alert(set.remove('abc')) alert(set.remove('abc')) alert(set.values()) //4.has方法 alert(set.has('abc')) //5.获取元素的个数 alert(set.size()) set.clear() alert(set.size())

集合中的操作:

//集合间操作 //1.并集 Set.prototype.union=function(otherSet){ //this:集合对象 A //otherSet:集合对象 B //1.创建一个新的集合 var unionSet=new Set() //2.将 a 集合中的所有元素添加到新集合中 var values=this.values() for(var i=0;i

测试:

//创建两个集合,并且添加元素 var setA=new Set() //setA.add('abc') setA.add('cba') setA.add('nba') var setB=new Set() setB.add('aaa') setB.add('nba') setB.add('cba') //2.求两个集合的并集 unionSet=setA.union(setB) alert(unionSet.values()) //3.求两个集合的交集 var intersectionSet=setA.intersection(setB) alert(intersectionSet.values()) //4.求两个集合的差集 var differenceSet=setA.difference(setB) alert(differenceSet.values()) //5.判断子集 alert(setA.subSet(setB))

封装字典类:

//封装字典类 function Dictionary(){ //字典属性 this.items={} //字典的操作方法 //1.在字典中添加键值对 Dictionary.prototype.set=function(key,value){ this.items[key]=value } //2.判断字典中是否有某个 key Dictionary.prototype.has=function(key){ return this.items.hasOwnProperty(key) } //3.从字典中移除元素 Dictionary.prototype.remove=function(key){ //1.判断字典中是否有这个 key if(!this.has(key)) return false //2.从字典中删除 key delete this.items[key] return true } //4.根据 key 获取 value Dictionary.prototype.get=function(key){ return this.has(key)?this.items[key]:undefined } //5.获取所有的 keys Dictionary.prototype.keys=function(){ return Object.keys(this.items) } //6.size方法 Dictionary.prototype.keys=function(){ return this.keys().length } //7.clear方法 Dictionary.prototype.clear=function(){ this.items={} } }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:威少前往湖人,与詹姆斯、浓眉组成三巨头!
下一篇:javascript hash 函数
相关文章

 发表评论

暂时没有评论,来抢沙发吧~