跳到主要内容

字典(Dictionary)

========== 在 JavaScript 中,字典与对象很相似。字典中有几个属性:

  • set(key,value) 向字典中添加新元素;
  • delete(key) 通过字典的键值从字典中移除对应的数据;
  • get(key) 通过键值获取对应的数据;
  • clear() 将这个字典中所有元素删除;
  • size() 返回字典所包含的元素个数;
  • keys() 将字典中所含的所有的键名以数组形式返回;
  • values() 将字典中所含的所有的键名对应的值以数组形式返回;
  • has(key) 如果某个键值存在于这个字典中,则返回 true

创建字典

const Dictionary = (function(){
var _this[_map] = Symbol();
class Dictionary{
this[_this[_map]] = {};
// ... 字典方法
}
return Dictionary;
});

这里还是使用 匿名函数 + ES6 类 的形式实现。

set(key,value) 添加元素

set(key,value){
this[_map][key] = value;
}

或这在 set() 方法最后写上 return this; 这样就可以做到 链式调用:

var this[_map] = new Dictionary();
this[_map].set('a',1).set('b',2);

通过键值获取对应的数据 —— get(key)

get(key){
this[_map][key] ? this[_map][key] : undefined;
}

有就返回,没有返回 undefined

通过字典的键值从字典中移除对应的数据 —— delete(key)

delete(key){
if(this.has(key)){
delete this[_map][key];
}else{
return false;
}
}

如果某个键值存在于这个字典中,则返回 true —— has(key)

has(key){
return (key in this[_map]);
}

将字典中所含的所有的键名以数组形式返回 —— keys()

keys(){
return Object.keys(this[_map]);
}

这里用了 ES6 中的 Object.keys(object) 方法,该方法可以遍历出传入的对象中的所有属性名,将属性名保存在一个数组当中并返回。

返回字典所包含的元素个数 —— size()

可以利用上面的 Object.keys(object) 方法来实现:

size(){
return Object.keys(this[_map]).length;
}

values() 方法:

values(){
return Object.values(this[_map]);
}

这里也是用了 ES6 中的 Object 新增的方法。可以获取一个对象中所有属性值,并以数组形式返回。当然,也可以使用 for-in 循环来实现:

values(){
var arr = [];
for(let prop in this[_map]){
if(this.has(prop)){
arr.push(this[_map][prop]);
}
}
return arr;
}

clear() —— 清空字典

clear(){
for(let props in this[_map]){
this.delete(props);
}
}

最后还可以实现一个 getItems() 方法,返回字典中所有的 key-value 数据:

getItems(){
return this[_map];
}