JavaScript字典

在字典中,咱們使用鍵值對來存儲數據。
this

字典

字典的定義

Dictionary (map, association list) is a data structure, which is generally an association of unique keys with some values. One may bind a value to a key, delete a key (and naturally an associated value) and lookup for a value by the key.spa

字典中存儲的是[key,value],其中鍵名是用來查詢特定的元素的。字典和集合很類似,只是集合以[value,value]的格式來存儲數據的。字典也叫做映射。code

JavaScript實現的字典

下面經過一個實際例子來建立而且使用一下字典。對象

首先建立一個字典:
索引

function Dictionary(){

    var items = {};

    this.set = function(key, value){
        items[key] = value; //以鍵做爲索引來存儲數據
    };

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

    this.has = function(key){
        return items.hasOwnProperty(key);
        //return value in items;
    };

    this.get = function(key) {
        return this.has(key) ? items[key] : undefined;
    };

    this.clear = function(){
        items = {};
    };

    this.size = function(){
        return Object.keys(items).length;
    };

    this.keys = function(){
        return Object.keys(items);
    };

    this.values = function(){
        var values = [];
        for (var k in items) {
            if (this.has(k)) {
                values.push(items[k]);
            }
        }
        return values;
    };

    this.each = function(fn) {
        for (var k in items) {
            if (this.has(k)) {
                fn(k, items[k]);
            }
        }
    };

    this.getItems = function(){
        return items;
    }
}

簡單地使用字典

接下來咱們使用這個建立好的字典來存儲一些郵件地址的數據吧,相似一個簡易的電子郵件薄:
ip

var dictionary = new Dictionary();
dictionary.set('Gandalf', 'gandalf@email.com');
dictionary.set('John', 'johnsnow@email.com');
dictionary.set('Tyrion', 'tyrion@email.com');
console.log(dictionary.has('Gandalf'));   
console.log(dictionary.size());  
console.log(dictionary.keys()); 
console.log(dictionary.values()); 
console.log(dictionary.get('Tyrion')); 
dictionary.remove('John');
console.log(dictionary.keys()); 
console.log(dictionary.values()); 
console.log(dictionary.getItems()); //打印輸出items對象的內部結構

輸出的結果以下:ci

相關文章
相關標籤/搜索