欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

javascript仿es6的map类

程序员文章站 2022-06-22 20:28:07
var Dictionary = (function (){ var f = function(){ this._items = {}; }; var proto = f.prototype; proto.has = function(key){ return key in this... ......
 var Dictionary = (function (){
        var f = function(){
            this._items = {};
        };
        var proto = f.prototype;
        proto.has = function(key){
            return key in this._items;
        }
        proto.set = function(key,value){
            this._items[key] = value;
        }
        proto.remove = function(key){
            if(this.has(key)){
                delete this._items[key];
                return true;
            }
            return false;
        }
        proto.get = function(key){
            return this.has(key) ? this._items[key] : undefined;
        };
        proto.values  = function (){
            var values = [];
            for(var k in this._items){
                if(this.hsa(k)){
                    values.push(this._items[k]);
                }
            }
            return values;
        };
        proto.clear = function(){
            this._items = {};
        };
        proto.size = function(){
            var count = 0;
            for(var prop in this._items){
                if(this._items.hasOwnProperty(prop)){
                     ++ count;
                }
            }
            return count;
        };
        proto.keys = function(){
            var keys = [];
            for(var prop in this._items){
                if(this._items.hasOwnProperty(prop)){
                    keys.push(prop);
                }
            }
            return keys;
        };
        proto.getItems = function(){
            return this._items;
        }
        return f;
    })();