前言
集合就是数学中的集合概念, 只不过用到了编程语言中. 也就是Set类
(www.hedaoshe.com)
概念: 由一组无序且唯一的项组成.
正文
下面就让我们来实现Set类
class MySet{
items = {} //存放数据的对象, 这次使用的是对象来存放, 而不是数组, 主要是对象更方便
//集合是否存放了这个数据
has(value){
return this.items.hasOwnProperty(value)
}
//在集合中添加一个数据
add(value){
if(!this.has(value)){
this.items.
}
}
//移除集合中某个元素
remove(value){
if(!this.has(value)){
delete this.items[value]
return true
}
return false
}
//移除集合中所有元素
clear(){
this.items = {}
}
//获得集合中元素个数
size(){
return Object.keys(this.items).length
}
//获得集合中所有元素
values(){
return Object.keys(this.items)
}
//下面实现集合的 并集 交集 合集 子集
//并集
union(otherSet){
const unionSet = new MySet()
const selfSetValues = this.values()
for(let selfVal of selfSetValues){
unionSet.add(selfVal)
}
const otherSetValues = otherSet.values()
for(let otherVal of otherSetValues){
unionSet.add(otherVal)
}
return unionSet
}
//交集
intersection(otherSet){
const intersectionSet = new MySet()
const selfSetValues = this.values()
for(let selfVal of selfSetValues){
if(otherSet.has(selfVal)){
intersectionSet.add(selfVal)
}
}
return intersectionSet
}
//差集(本集合和另一个集合不同的元素)
difference(otherSet){
const differenceSet = new MySet()
const selfSetValues = this.values()
for(let selfVal of selfSetValues){
if(!otherSet.has(selfVal)){
differenceSet.add(selfVal)
}
}
return differenceSet
}
//子集(判断本集合是否是另一个集合的子集)
isSub(otherSet){
if(this.size()>otherSet.size()){
return false
}
const selfSetValues = this.values()
for(let selfVal of selfSetValues){
if(!otherSet.has(selfVal)){
return false
}
}
return true
}
}
注意: ①
in关键字
遍历items对象时, 会把items继承的类属性也找出来, 而hasOwnProperty方法
和of关键字
只会遍历item对象本身的属性, 所以我没用in关键字
结尾
今天我们实现了集合这种数据结构, 大家对集合这种数据结构也有了更深刻的认识.