字典數據結構(Map、WeakMap)

代碼實現:

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'));

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章