在字典中,我们利用[键,值]的形式来存储数据,字典和集合很相似,集合以[值,值]的形式存储元素,字典以[键,值]的形式来存储元素,也成映射
window.onload = function() {
var dictionary = new Dictionary();
dictionary.set('Baidu', 'www.baidu.com');
dictionary.set('QQ', 'www.qq.com');
dictionary.set('Wangyi', 'www.163.com');
console.log(typeof dictionary); // object
console.log(dictionary.has('Baidu')); //true
console.log(dictionary.has('Alibaba')); //false
console.log(dictionary.keys());
console.log(dictionary.values());
console.log(dictionary.get('QQ'));
};
function Dictionary() {
var items = {};
this.has = function(key){
return key in items;
};
this.set = function(key, value){
items[key] = value;
};
this.delete = function(key) {
if (this.has(key)) {
delete items[key];
return true;
}
return false;
};
this.get = function(key) {
return this.has(key)? items[key] : undefined;
};
this.values = function() {
var values = [];
for(var i in items) {
if(this.has(i)) {
values.push(items[i]);
}
}
return values;
};
this.keys = function() {
return Object.keys(items);
};
this.getItems = function() {
return items;
}
}