字典定义
即ES6中的Map;字典也称为映射
创建一个字典
function Dictionary(){
var items={}
}
常用方法实现
has()判断某个键值是否存在字典中
this.has=function(key){
return key in items;
}
set()添加新元素
this.set=function(key,value){
items[key]=value;
}
remove()根据键值来移除字典中的元素
this.remove=function(key){
if(this.has(key)){
delete items[key];
return true;
}else{
return false;
}
}
get()根据键值来获取特定的元素值
this.get=function(key){
return this.has(key)?items[key]:undefined
}
clear()清除字典中的所有元素
this.clear=function(){
return items={}
}
size()返回字典中所有元素的个数
this.size=function(){
let count=0
for(let prop in items){
if(items.hasOwnProperty(prop)){
++count
}
}
return count
}
keys()将字典中所有键值以数组形式返回
this.keys=function(){
var keys=[];
for(var k in items){
if(this.has(k)){
keys.push(k);
}
}
return keys;
}
values()将字典中所有数值以数组形式返回
this.values=function(){
var values=[];
for(var k in items){
if(this.has(k)){
values.push(items[k]);
}
}
return values;
}
测试代码
let dictionary=new Dictionary()
dictionary.set('hername','YanHilin')
dictionary.set('age',20)
console.log(dictionary.size())//2
console.log(dictionary.has('age'))//true
console.log(dictionary.get('hername'))//YanHilin
console.log(dictionary.keys())//(2) ["hername", "age"]
console.log(dictionary.values())//(2) ["YanHilin", 20]
dictionary.clear()
console.log(dictionary.values())//[]