javaScript数据结构--字典

在字典中存储的值是【键、值】对,字典和集合很相似,集合以【值、值】的形式存储。字典也称作映射。

字典的代码实现:

function Dictionary() {

    var items = {};

    this.set = function(key, value) {

        if(!this.has()) {

            items[key] = value;

            return true;

        }else {

            return false;

        }

    }

    this.remove = function(key) {

        if(this.has(key)) {

            delete items[key];

            return true;

        }else {

            return false;

        }

    }

    this.has = function(key) {

        return key in items;

    }

    this.get = function(key) {

        return this.has(key) ? items[key] : null;

    }

    this.clear = function() {

        items = [];

    }

    this.size = function() {

        return Object.keys().length;

    }

    this.keys = function() {

        return Object.keys();

    }

    this.values = function() {

        const  values = [];

        for(var k in items) {

            values.push(items[k]);

        }

        return values;

    }

}

var dic = new Dictionary();

dic.set('a', '一');

dic.set('b', '二');

dic.set('c', '三');

console.log(dic.values()); // [ '一', '二', '三' ]

dic.remove('b');

console.log(dic.values()); // [ '一', '三' ]

console.log(dic.get('c')); // 三

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容