1.字典概述
- 一种以 键-值 对存在的数据结构,JavaScript的 Object 就是以字典形式设计的。
- 可以用数组和对象实现,可以自定义Dictionary类实现。
2.Dictionary类
function Dictionary () {
this.datastore = new Array()
this.add = add
this.find = find
this.remove = remove
this.showAll = showAll
function ... (){}
}
前置知识
let arr = new Array()
arr['abc'] = 123
arr[0] // undefined
arr['abc'] // 123
delete arr.abc // true
arr // true
1.数组也是对象,不一定非用下标方式
2.delete 可以去掉对象属性
方法实现
function add (key, value) {
this.datastore[key] = value
}
function find (key) {
return this.datastore[key]
}
function remove (key) {
delete this.datastore[key]
}
function showAll () {
for (let key of Object.keys(this.datastore)) {
console.log((key + " -> " + this.datastore[key]))
}
}
let pbook = new Dictionary()
pbook.add('wayliu', '123')
pbook.add('liuguowei', '456')
console.log(pbook.datastore) // [ wayliu: '123', liuguowei: '456' ]
console.log(Object.keys(pbook.datastore)) // [ 'wayliu', 'liuguowei' ]
pbook.showAll()
//
wayliu -> 123
liuguowei -> 456
for-of 遍历的是值,通过遍历Object.keys(this.datastore)即[ ‘wayliu’, ‘liuguowei’ ],所以
console.log((key + " -> " + this.datastore[key]))中key即wayliu与liuguowei,datastore[key]即数组对应的值。
3.Dictionary 类的辅助方法
- 获取字典中元素个数 count()
- 清空字典元素
function count () {
let n = 0;
for (let key of (Object).keys(this.datastore)) {
n++
}
return n
}
function clear () {
for (let key of (Object).keys(this.datastore)) {
delete this.datastore[key]
}
}
let pbook = new Dictionary()
pbook.add('wayliu', '123')
pbook.add('liuguowei', '456')
console.log(pbook.count()) // 2
pbook.clear()
console.log(pbook.count()) // 0