一、认识集合
集合通常是由一组无序的
,不能重复
的元素构成。通常使用 哈希表
来实现
二、集合的封装
在 ES6
中,Set
数据结构其实就是这样一种结构。但是我们还是来自定义的封装一下,来熟悉集合结构。
class Set{
constructor(){
this.items = {}
}
// 添加一个新的项
add(value){
if(this.has(value)) return false
this.items[value] = value
return true
}
has(value){
return this.items.hasOwnProperty(value)
}
remove(value){
if(!this.has(value)) return false
delete this.items[value]
return true
}
clear(){
this.items = {}
}
size(){
return Reflect.ownKeys(this.items).length
}
}
const h = new Set()
h.add('dfa')
h.add('df')
h.add('gg')
h.remove('gg')
console.log(h.size())
三、集合间的操作
集合间有并集
、交集
、差集
、子集
几种操作。
class Set{
constructor(){
this.items = {}
}
// 添加一个新的项
add(value){
if(this.has(value)) return false
this.items[value] = value
return true
}
has(value){
return this.items.hasOwnProperty(value)
}
remove(value){
if(!this.has(value)) return false
delete this.items[value]
return true
}
clear(){
this.items = {}
}
size(){
return Reflect.ownKeys(this.items).length
}
// 集合中所有的值
values(){
return Reflect.ownKeys(this.items)
}
// 并集
union(otherSet){
// 1、创建新集合
let unionSet = new Set()
// 2、将集合 A 中的所有元素添加到新集合中
this.values().forEach(function(v){
unionSet.add(v)
})
// 取出 B 集合中的元素,判断是否需要添加到新集合中
otherSet.values().forEach(function(v){
unionSet.add(v)
})
return unionSet
}
// 交集
intersection(otherSet){
let intersectionSet = new Set()
const values = this.values()
values.forEach(function(v){
if(otherSet.has(v)){
intersectionSet.add(v)
}
})
return intersectionSet
}
// 差集
difference(otherSet){
let differenceSet = new Set()
// 判断 A 集合中的元素是否同时存在于 B 集合中,不存在则添加到新集合中
const values = this.values()
values.forEach(function(v){
if(!otherSet.has(v)){
differenceSet.add(v)
}
})
return differenceSet
}
// 子集
subset(otherSet){
// 遍历 A 中的所有元素,如果发现,集合 A 中的元素,在集合 B 中不存在,那么返回 false
// 如果遍历完了整个集合,依然没有返回 false,那么返回 true, 说明 A 是 B 的子集
const values = this.values()
for(let i = 0; i < values.length; i++){
let item = values[i]
if(!otherSet.has(item)) return false
}
return true
}
}
const A = new Set()
A.add('dfa')
A.add('df')
A.add('gg')
const B = new Set()
B.add('pp')
B.add('kk')
B.add('dfa')
B.add('df')
B.add('gg')
console.log(B.subset(A))
四、字典
字典的特点:
- 字典的主要特点是
一一对应
的关系 - 使用字典的方式:
{age: 18, name: 'Jack'}
,可以通过 key 取出 value - 字典中的
key 是不可以重复的
,而value 可以重复
,并且字典中的key 是无序的
在 JavaScript
中,似乎对象本身就是一种字典。这里就不再展开实现了