代碼實現:
var Dictionary = function() {
var items = {};
// has 判斷是否有某屬性
this.has = function(key) {
// return items.hasOwnProperty(key);
return key in items;
}
// set 添加新的鍵值對
this.set = function(key, value) {
items[key] = value
}
// delete 刪除鍵值對
this.delete = function(key) {
if(this.has(key)) {
delete items[key];
return true;
}
return false;
}
// get 獲取鍵值對
this.get = function(key) {
if(this.has(key)) {
return items[key];
}
return undefined;
}
}
var dictionary = new Dictionary();
dictionary.set('name','John');
dictionary.set('age','12');
console.log(dictionary.has('name'));
console.log(dictionary.has('work'));
console.log(dictionary.get('name'));
console.log(dictionary.get('work'));
console.log(dictionary.delete('name'));
console.log(dictionary.delete('work'));