基础数据结构--手动实现字典及其相关方法

字典的定义:字典是一种以键–值来存储数据的数据结构。但是他的基础是Array,而不是Object.但是字典也是无序的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function Dictionary () {
// 像字典中添加健--值
this.add = add
// 保存数据
this.dataStore = new Array
// 查找键值
this.find = find
// 删除某一项
this.remove = remove
// 统计字典中的属性个数
this.count = this.count
// 清空字典
this.clear = clear
// 显示字典中所有的项
this.showAll = showAll
}
function add (key, value) {
this.dataStore[key] = value
}
function find (key) {
return this.dataStore[key]
}
function remove (key) {
delete this.dataStore[key]
}
function count () {
let n = 0
for (let key in Object.keys(this.dataStore)) {
++n
}
return n
}
function clear () {
Object.keys(this.dataStore).forEach(key => {
delete this.dataStore[key]
})
}
function showAll () {
for (let key in Object.keys(this.dataStore).sort()) {
console.log(this.dataStore[key])
}
}

注:字典的实现还是相对比较简单的。但是字典和对象一样,是无序的,需要自己排序。

  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2022 Lee
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信