数据结构篇——字典

字典是一种以键值对形式存储数据的数据结构,JavaScript的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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
function Dictionary(){
this.dataStore = new Array();
this.add = add;
this.find = find;
this.remove = remove;
this.showAll = showAll;
this.count = count;
this.clear = clear;
}

// 向字典中添加键值对
function add(key, value){
this.dataStore[key] = value;
}

// 通过键返回值
function find(key){
return this.dataStore[key];
}

// 通过键删除键值对
function remove(key){
delete this.dataStore[key];
}

function showAll() {
if (Object.keys(this.dataStore).length == 0){
console.log('null')
}
for (let key of Object.keys(this.dataStore).sort()) { // 对键值进行排序
console.log(key + '->' + this.dataStore[key]);
}
}

function count(){
return Object.keys(this.dataStore).length;
// 方法二
// let n = 0;
// for (let key in Object.keys(this.dataStore)){
// n++;
// }
// return n;
}

function clear(){
for(let key of Object.keys(this.dataStore)){
delete this.dataStore[key];
}
}

// 测试代码
let book = new Dictionary();
book.add('c', '1');
book.add('b', '2');
book.add('a', '3');
console.log('a的值为:'+book.find('a'));
book.remove('b')
console.log(book.count());
book.showAll();
book.clear();
book.showAll();
console.log(book.count());