-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdictionary.js
More file actions
81 lines (65 loc) · 1.61 KB
/
dictionary.js
File metadata and controls
81 lines (65 loc) · 1.61 KB
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
function Dictionary () {
var items = {}
this.has = function (key) {
// 书上用的是in操作符来判断,但是in对于继承来的属性也会返回true,所以我换成了这个
return items.hasOwnProperty(key)
}
this.set = function (key, value) {
items[key] = value
}
this.remove = function (key) {
if (this.has(key)) {
delete items[key]
return true
}
return false
}
this.get = function (key) {
return this.has(key) ? items[key] : undefined
}
// 自己实现的
// this.values = function () {
// var valueArr = []
// var keyArr = Object.keys(items)
// for (var i = 0; i < keyArr.length; i++) {
// valueArr[i] = items[keyArr[i]]
// }
// return valueArr
// }
this.values = function () {
var values = []
for (var k in items) {
if (this.has(k)) {
values.push(items[k])
}
}
return values
}
this.keys = function () {
return Object.keys(items)
}
this.size = function () {
return Object.keys(items).length
}
this.clear = function () {
items = {}
}
this.getItems = function () {
return items
}
}
// 一些操作
// var dictionary = new Dictionary()
// dictionary.set('A', '1')
// dictionary.set('B', '2')
// dictionary.set('C', '3')
// console.log(dictionary.has('A'))
// console.log(dictionary.size())
// console.log(dictionary.keys())
// console.log(dictionary.values())
// console.log(dictionary.get('C'))
// dictionary.remove('B')
// console.log(dictionary.keys())
// console.log(dictionary.values())
// console.log(dictionary.getItems())
module.exports = Dictionary