字典的結構
function Dictionary () {
this.items = {};
if(typeof this.set != 'function') {
Dictionary.prototype.has = function(key) {};
Dictionary.prototype.set = function(key, value) {};
Dictionary.prototype.remove = function(key) {};
Dictionary.prototype.get = function(key) {};
Dictionary.prototype.values = function() {};
Dictionary.prototype.keys = function() {};
Dictionary.prototype.clear = function() {};
Dictionary.prototype.size = function() {};
Dictionary.prototype.getItems = function() {}
}
}
- set(key,value):向字典中添加新元素。
- remove(key):通過使用鍵值來從字典中移除鍵值對應的數據值。
- has(key):如果某個鍵值存在於這個字典中,則返回true,反之則返回false。
- get(key):通過鍵值查找特定的數值並返回。
- clear():將這個字典中的所有元素全部刪除。
- size():返回字典所包含元素的數量。與數組的length屬性類似。
- keys():將字典所包含的所有鍵名以數組形式返回。
- values():將字典所包含的所有數值
源代碼
function Dictionary () {
this.items = {};
if(typeof this.set != 'function') {
Dictionary.prototype.has = function(key) {
return key in this.items;
};
Dictionary.prototype.set = function(key, value) {
this.items[key] = value;
};
Dictionary.prototype.remove = function(key) {
if(this.has(key)) {
delete this.items[key];
return true;
}
return false;
};
Dictionary.prototype.get = function(key) {
return this.has(key) ? this.items[key] : 'undefined';
};
Dictionary.prototype.values = function() {
var values = [];
for(var k in this.items) {
if(this.has(k)) {
values.push(this.items[k]);
}
}
return values;
};
Dictionary.prototype.keys = function() {
var keys = [];
for(var k in this.items) {
if(this.has(k)) {
keys.push(k);
}
}
return keys;
};
Dictionary.prototype.clear = function() {
this.items = {};
};
Dictionary.prototype.size = function() {
var count = 0;
for(var k in this.items) {
if(this.items[k]) {
count++;
}
}
return count;
};
Dictionary.prototype.getItems = function() {
return this.items;
}
}
}