
js中set集合是什么呢?不知道的小伙伴来看看小编今天的分享吧!
1、set集合的定义
集合成员是无序的,是不重复的一组成员。
开发中可用于去除重复数据
set集合和map不一样。这里只实现了set集合的方法。
map是用哈希结构的定义来实现的,本质上也是对数组和链的结合。

2、封装对象
此处用对象的方式来实现集合
function Set(){
this.items={}
}3、新增值
默认set的健名是其健值
Set.prototype.add=function(value){
if(this.has(value)){
return false
}
this.items[value]=value
return true
}4、删除值
Set.prototype.has=function(value){
return this.items.hasOwnProperty(value)
}
Set.prototype.remove=function(value){
if(!this.has(value)){
return false
}
delete this.items[value]
return true
}5.一般方法
Set.prototype.clear=function(){
this.items={}
}
Set.prototype.size=function(){
return Object.keys(this.items).length
}
Set.prototype.values=function(){
return Object.keys(this.items)
}6、并集
Set.prototype.union=function(otherSet){
var unionSet=new Set()
var values=this.values()
for(var i=0;i<values.length;i++){
unionSet.add(values[i])
}
values=otherSet.values()
for(var i=0;i<values.length;o++){
unionSet.add(values[i])
}
return unionSet
}7、交集
Set.prototype.intersection=function(otherSet){
var intersectionSet=new Set()
var values=this.values()
for(var i=0;i<values.length;i++){
var item=values[i]
if(otherSet.has(item)){
intersectionSet.add(item)
}
}
return intersectionSet
}8、补集
Set.prototype.difference=function(otherSet){
var differenceSet=new Set()
var values=this.values()
for(var i=0;i<values.length;i++){
var item=values[i]
if(!otherSet.has(item)){
differenceSet.add(item)
}
}
return differenceSet
}9、子集
Set.prototype.subset=function(otherSet){
var values=this.values()
for(var i=0;i<values.length;i++){
var item=values[i]
if(!otherSet.has(item)){
return false
}
}
return true
}以上就是小编今天的分享了,希望可以帮助到大家。
