数据结构之字典

版权声明:Oreo https://blog.csdn.net/weixin_43154931/article/details/82821565

JavaScript实现字典

  • 字典数据结构
  • 创建字典

1. 链表数据结构
在计算机科学中,关联数组(英语:Associative Array),又称映射(Map)、字典(Dictionary)是一个抽象的数据结构,它包含着类似于(键,值)的有序对。

完整代码


const Dictionary = function() {
    let items = {},
        length = 0;

    this.set = function(key, value) {
        items[key] = value;
        length++;
    }
    this.delete = function(key) {
        if (this.has(key)) {
            delete items[key];
            length--;
            return true;
        }
        return false;
    }

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

    this.get = function(key) {
        // 通过键值查找特定的数值并fa
        return this.has(key) ? items[key] : undefined;
    }

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

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

    this.keys = function() {
        // 将字典所包含的所有key以数组的形式返回
        let keys = [];
        for (let k in items) {
            if (this.has(k)) {
                keys.push(k);
            } 
        }
        return keys;
       
    }

    this.values = function() {
        // 将字典所包含的所有value以数组的形式返回
        let values = [];
        for (let k in items) {
            if (this.has(k)) {
                values.push(items[k]);
            }
        }
        return values;
       
    }

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

猜你喜欢

转载自blog.csdn.net/weixin_43154931/article/details/82821565
今日推荐