字典

字典

我们已经知道,集合表示一组互不相同的元素(不重复的元素)。在字典中,存储的是[键, 值]对,其中键名是用来查询特定元素的。字典和集合很相似,集合以[值, 值]的形式存储元素,字典则以[键, 值]的形式来存储元素。字典也称作映射符号表关联数组

Dictionary类的模拟实现

与Set类类似,ECMAScript 2015同样包含了一个Map类的实现,即我们所说的字典,下面我们以ECMAScript 2015中Map类的实现为基础,模拟实现自己的Dictionary类。

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
function defaultToString(item) {
if (item === null) {
return "NULL";
} else if (item === undefined) {
return "UNDEFINED";
} else if (typeof item === "string" || item instanceof String) {
return `${item}`;
}
return item.toString();
}
class ValuePair {
constructor(key, value) {
this.key = key;
this.value = value;
}
toString() {
return `[#${this.key}: ${this.value}}]`;
}
}
class Dictionary {
// 构造函数
constructor(toStrFn = defaultToString) {
this.toStrFn = toStrFn;
this.table = {};
}
// 检测一个键是否存在于字典中
hasKey(key) {
return this.table[this.toStrFn(key)] != null;
}
// 在字典和ValuePair类中设置键和值
set(key, value) {
if (key != null && value != null) {
const tableKey = this.toStrFn(key);
this.table[tableKey] = new ValuePair(key, value);
return true;
}
return false;
}
// 从字典中移除一个值
remove(key) {
if (this.hasKey(key)) {
delete this.table[this.toStrFn(key)];
return true;
}
return false;
}
// 从字典中检索一个值
get(key) {
const valuePair = this.table[this.toStrFn(key)];
return valuePair == null ? undefined : valuePair.value;
}
// 将字典中所有[键, 值]对返回
keyValues() {
return Object.values(this.table);
}
// 将字典所包含的所有键名以数组形式返回
keys() {
return this.keyValues().map(valuePair => valuePair.key);
}
// 将字典所包含的所有数值以数组形式返回
values() {
return this.keyValues().map(valuePair => valuePair.value);
}
// 迭代字典中所有的键值对
forEach(callbackFn) {
const valuePairs = this.keyValues();
for (let i = 0; i < valuePairs.length; i++) {
const result = callbackFn(valuePairs[i].key, valuePairs[i].value);
if (result === false) {
break;
}
}
}
// 返回字典所包含值的数量
size() {
return Object.keys(this.table).length;
}
// 检验字典是否为空
isEmpty() {
return this.size() === 0;
}
// 清空字典
clear() {
this.table = {};
}
// 将字典转换为字符串
toString() {
if (this.isEmpty()) {
return "";
}
const valuePairs = this.keyValues();
let objString = `${valuePairs[0].toString()}`;
for (let i = 1; i < valuePairs.length; i++) {
objString = `${objString}, ${valuePairs[i].toString()}`
}
return objString;
}
}

这里就不再演示Dictionary类中方法的使用了,有兴趣的可以自己做个demo测试一下,如果有任何的问题,欢迎评论区留言。

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2020-2021 Sanmu
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信