ITPub博客

首页 > IT职业 > IT职场 > javascript实现Map结构

javascript实现Map结构

IT职场 作者:joytoy 时间:2021-09-09 10:06:57 0 删除 编辑

//定义map    function Map() {    this.container = {};}//将key-value放入map中    Map.prototype.put = function(key, value) {    try {        if (key != null){            this.container[key] = value;        }    } catch (e) {        return e;    }};//根据key从map中取出对应的value    Map.prototype.get = function(key,deft) {    if(!this.containsKey(key)){        return deft;    }    try {        return this.container[key];    } catch (e) {        return e;    }};//判断map中是否包含指定的key    Map.prototype.containsKey = function(key) {    try {        for ( var p in this.container) {            if (p == key)                return true;        }        return false;    } catch (e) {        return e;    }}//判断map中是否包含指定的value    Map.prototype.containsValue = function(value) {    try {        for ( var p in this.container) {            if (this.container[p] === value)                return true;        }        return false;    } catch (e) {        return e;    }};//删除map中指定的key    Map.prototype.remove = function(key) {    try {        delete this.container[key];    } catch (e) {        return e;    }};//清空map    Map.prototype.clear = function() {    try {        delete this.container;        this.container = {};    } catch (e) {        return e;    }};//判断map是否为空    Map.prototype.isEmpty = function() {    if (this.keySet().length == 0)        return true;    else        return false;};//获取map的大小    Map.prototype.size = function() {    return this.keySet().length;}//返回map中的key值数组    Map.prototype.keySet = function() {    var keys = new Array();    for ( var p in this.container) {        keys.push(p);    }    return keys;}//遍历MapMap.prototype.each = function(fun){    var keys = this.keySet();    for(var i = 0;i < keys.length;i++){        fun(keys[i],this.get(keys[i]));    }}//返回map中的values值数组    Map.prototype.values = function() {    var valuesArray = new Array();    var keys = this.keySet();    for (var i = 0; i < keys.length; i++) {        valuesArray.push(this.container[keys[i]]);    }    return valuesArray;}//获取Map的最大值,参数为比较函数Map.prototype.max = function(compare){    var keys = this.keySet();    var maxKey = keys[0],maxValue = this.get(keys[0]);    for(var i = 0;i < keys.length;i++){        if(compare(this.get(keys[i],maxValue))){            maxValue = this.get(keys[i]);            maxKey = keys[i];        }    }    return [maxKey,maxValue];}//返回 map 中的 entrySet 对象Map.prototype.entrySet = function() {    var array = new Array();    var keys = this.keySet();    for (var i = 0; i < keys.length; i++) {        array.push(keys[i],this.container[keys[i]]);    }    return array;}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4650/viewspace-2816681/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2018-08-12

  • 博文量
    97
  • 访问量
    18297