前言
集合是没有重复值且有顺序的数据结构
实现思路和代码
集合类
function Set() {
this.items = {
}
}
基础集合具备以下方法
- 判断元素是否在集合中
has(value) {
//使用对象原型方法判断元素是否在集合中
return this.items.hasOwnProperty(value)
}
- 集合中添加元素
add(value) {
//判断集合中是否存在要添加的元素
if(this.has(value)) {
return false
}
//添加元素到集合中
this.items[value] = value
return true
}
- 删除集合中的元素
remove(value) {
//判断集合中是否存在要删除的元素
if(!this.has(value)) {
return false
}
delete this.items[value]
return trues
}
- 清空集合
clear() {
this.items = {
}
}