常用方法:
- set(key, value) 添加键值对
- has(key)判断字典中是否有某个key
- remove(key)从字典中移除元素remove
- get(key) 根据key去获取value
- keys() 获取多有的keys
- values()获取所有的value
- size() 查看大小
- clear()方法
// 封装字典
// 创建字典的构造函数
function Dictionary() {
// 字典属性
this.items = {}
// 字典操作方法
// 1 添加键值对
Dictionary.prototype.set = function (key, value) {
this.items[key] = value;
}
// 2 判断字典中是否有某个key
Dictionary.prototype.has = function (key) {
return this.items[key] != null
}
// 3 从字典中移除元素remove
Dictionary.prototype.remove = function (key) {
delete this.items[key]
return true
}
// 4 根据key去获取value
Dictionary.prototype.get = function (key) {
return this.has(key) ? this.items[key] : undefined
}
// 5 获取多有的keys
Dictionary.prototype.keys = function () {
return Object.keys(this.items)
}
// 6 获取所有的value
Dictionary.prototype.values = function () {
return Object.values(this.items)
}
// 7 size方法
Dictionary.prototype.size = function () {
// return Object.keys(this.items).length
return this.keys().length
}
// 8 clear方法
Dictionary.prototype.clear = function () {
this.items = {}
}
}
// export function Dictionary()
// export {Dictionary}
// module.exports = {Dictionary}
// // 测试
// // 插入值
// let dic = new Dictionary();
// dic.set("a", 123);
// dic.set("b", 456);
// dic.set("c", 789);
// dic.set("d", "qwe");
// console.log(dic);
// console.log(dic.has("a"));
// console.log(dic.has("f"));
// console.log(dic.has(999));
// console.log(dic.get("a"));
// console.log(dic.get(999));
// console.log(dic.keys());
// console.log(dic.size());
// console.log(dic.values());
// dic.remove("d");
// console.log(dic.values());
// dic.clear();
// console.log(dic.values());