字典
集合、字典、散列表都可以存储不重复的数据。字典和我们上面实现的集合很像,上面的集合中我们以{ value: value }
的形式存储数据,而字典是以{ key: value }
的形式存储数据,字典也称作映射。
简单说:Object
对象便是字典在 Javascript 中的实现。
简单实现一个字典类:
class Dictionary {
constructor() {
this.items = {}
}
set(key, value) {
this.items[key] = value
}
get(key) {
return this.items[key]
}
remove(key) {
delete this.items[key]
}
get keys() {
return Object.keys(this.items)
}
get values() {
/*
也可以使用ES7中的values方法
return Object.values(this.items)
*/
// 在这里我们通过循环生成一个数组并输出
return Object.keys(this.items).reduce((r, c, i) => {
r.push(this.items[c])
return r
}, [])
}
}
使用字典类:
const dictionary = new Dictionary()
dictionary.set('Gandalf', '[email protected]')
dictionary.set('John', '[email protected]')
dictionary.set('Tyrion', '[email protected]')
console.log(dictionary)
console.log(dictionary.keys)
console.log(dictionary.values)
console.log(dictionary.items)