js数据结构Map -----字典

// Map
        function Dictionary() {
            var items = {};
            this.has = function (key) {
                return key in items;
            }
            this.set = function (key, value) {
                items[key] = value; //{1}
            }
            this.remove = function (key) {
                if (this.has(key)) {
                    delete items[key];
                    return true
                }
                return false
            }
            this.get = function (key) {
                return this.has(key) ? items[key] : undefined;
            };
            this.values = function () {
                var values = []
                for (var k in items) { //{1}
                    if (this.has(k)) {
                        values.push(items[k]); //{2}
                    }
                }
                return values;
            };
            this.getItems = function () {
                return items;
            }
            this.size = function(){
                return Object.keys(items).length
            }
            this.keys = function(){
                return Object.keys(items)
            }

        }
        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'));

  

posted @ 2018-09-07 10:23  Terre  阅读(891)  评论(0编辑  收藏  举报

风光无限好