原文:
概念:
集合、字典、散列表都可以存储不重复的数据。字典和我们上面实现的集合很像。
当然,字典中的数据具有不重复的特性。js 中 Object 的键值对 key: value 的形式就是字典的实现,所以字典通常也称为映射。
实现一个简单的字典类:
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 提供的 Object.values 方法
// return Object.values(this.items);
// 或者循环输出
return Object.keys(this.items).reduce((r, c, i) => {
r.push(this.items[c]);
return r;
}, [])
}
}
// 使用
let dictionary = new Dictionary();
dictionary.set('Gandalf', 'gandalf@email.com')
dictionary.set('John', 'johnsnow@email.com')
dictionary.set('Tyrion', 'tyrion@email.com')
console.log(dictionary)
console.log(dictionary.keys)
console.log(dictionary.values)
console.log(dictionary.items)
结构比较简单,需要注意的可能点是 key 相同的时候,后面添加的会覆盖前面的 value 值。