美文网首页前端技术讨论
javaScript数据结构--字典

javaScript数据结构--字典

作者: 安然_她 | 来源:发表于2019-05-14 13:29 被阅读0次

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

    字典的代码实现:

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

    相关文章

      网友评论

        本文标题:javaScript数据结构--字典

        本文链接:https://www.haomeiwen.com/subject/vwrsaqtx.html