JavaScript中的Map

1.首先,在新版本的浏览器中,已经实现了对Map的原生支持:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

 查看一下,哪个浏览器的版本支持了Map,并且想想自己所需要的最低版本是否已被支持。

2.若没有,自己实现一个:

function Map() { // 定义Map对象
    this.keys = new Array();
    this.data = new Object();

    this.put = function (key, value) {
        if (this.data[key] == null) {
            this.keys.push(key);
        }
        this.data[key] = value;
    };

    this.get = function (key) {
        return this.data[key];
    };

    this.remove = function (key) {
        this.keys.remove(key);
        this.data[key] = null;
    };

    this.each = function (fn) {
        if (typeof fn != 'function') {
            return;
        }
        var len = this.keys.length;
        for (var i = 0; i < len; i++) {
            var k = this.keys[i];
            fn(k, this.data[k], i);
        }
    };

    this.entrys = function () {
        var len = this.keys.length;
        var entrys = new Array(len);
        for (var i = 0; i < len; i++) {
            entrys[i] = {
                key: this.keys[i],
                value: this.data[i]
            };
        }
        return entrys;
    };

    this.isEmpty = function () {
        return this.keys.length == 0;
    };

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

var map = new Map();
map.put("a","a");
map.put("b","b");

var data = "";
map.each(function(value, key){
    data += key;
  }
);
console.log(data);
 

  

 

 

posted @ 2015-11-02 18:32  V!ncent  阅读(180)  评论(0编辑  收藏  举报