1. 程式人生 > >JavaScript 模擬 Dictionary

JavaScript 模擬 Dictionary

set script per clas ear asc delet value clear

function Dictionary() {
    var items = {};

    //判斷是否包含Key值
    this.has = function(key) {
        return key in items;
    };

    //賦值,添加鍵值對
    this.set = function(key, value) {
        items[key] = value;
    };

    //移除Key值
    this.remove = function(key) {
        if (this.has(key)) {
            delete items[key];
            return true;
        }
        return false;
    };

    //通過Key值獲取Value值
    this.get = function(key) {
        return this.has(key) ? items[key] : undefined;
    };

    //獲取所有的Key值
    this.keys = function() {
        var keys = [];
        for (var k in items) {
            keys.push(k);
        }
        return keys;
    };

    //獲取所有的Value值
    this.values = function() {
        var values = [];
        for (var k in items) {
            if (this.has(k)) {
                values.push(items[k]);
            }
        }
        return values;
    };

    //初始化鍵值對
    this.clear = function() {
        items = {};
    };

    //獲取鍵值對的個數
    this.size = function() {
        var count = 0;
        for (var prop in items) {
            if (items.hasOwnProperty(prop)) {++count;
            }
        }
        return count;
    };

    //獲取所有的鍵值對
    this.getItems = function() {
        return items;
    };
}

  

JavaScript 模擬 Dictionary