在字典中存储的值是【键、值】对,字典和集合很相似,集合以【值、值】的形式存储。字典也称作映射。
字典的代码实现:
function Dictionary() {
var items = {};
this.set = function(key, value) {
if(!this.has()) {
items[key] = value;
return true;
}else {
return false;
}
}
this.remove = function(key) {
if(this.has(key)) {
delete items[key];
return true;
}else {
return false;
}
}
this.has = function(key) {
return key in items;
}
this.get = function(key) {
return this.has(key) ? items[key] : null;
}
this.clear = function() {
items = [];
}
this.size = function() {
return Object.keys().length;
}
this.keys = function() {
return Object.keys();
}
this.values = function() {
const values = [];
for(var k in items) {
values.push(items[k]);
}
return values;
}
}
var dic = new Dictionary();
dic.set('a', '一');
dic.set('b', '二');
dic.set('c', '三');
console.log(dic.values()); // [ '一', '二', '三' ]
dic.remove('b');
console.log(dic.values()); // [ '一', '三' ]
console.log(dic.get('c')); // 三