javascript 封装一个类似Java中Map的对象

Java中的Map使用起来非常的方便,一时兴起使用JavaScript模拟了一个类似Java Map类的对象,可以直接像Java中使用Map那样使用,水平有限,不对之处望指出,后面加以修改,代码如下:

/**
 * @author CharlesRan
 * @since 2018.11.02
 */
/* 构造方法 */
function Map() {
    this.elements = [];
    this.indexBykey = -1;
}
Map.prototype.items = function() {
    return this.elements;
}
/**
 * 直接添加(不会覆盖已经存在的值)
 */
Map.prototype.add = function(obj) {
    this.elements.push(obj);
}
/**
 * 通过Key-val键-值队添加(Key值相同值覆盖)
 * 
 * @param key
 *            键
 * @param val
 *            值
 * @return null
 */
Map.prototype.put = function(key, val) {
    if (arguments.length == 2) {
        if (key && typeof key == "string" && (key + "").trim().length > 0) {
            if (this.containsKey(key)) {
                this.elements[this.indexBykey][key] = val;
            } else {
                var tempObj = {};
                tempObj[key] = val;
                this.elements.push(tempObj);
            }
        } else if (key == undefined)
            throw new Error("参数 1 是必须的");
        else if (typeof key != "string")
            throw new Error("参数1:类型错误期望类型是:string,实际传入类型为:" + typeof key);
        else
            throw new Error("参数 1 不能为空字符串或只包含空格的字符串");
    } else
        throw new Error("参数个数错误,期望参数个数为:2(key,value),实际传入参数个数为:1");
}
/* 返回map中元素的个数 */
Map.prototype.size = function() {
    return this.elements.length;
}
/* 通过index返回值 */
Map.prototype.getByIndex = function(index) {
    if (typeof index == "number") {
        if (index > this.elements.length - 1 || index < 0) {
            throw new Error("IndexOutOfBoundsException: " + index
                    + ",合法的参数范围为:0 到 " + (this.size() - 1));
        } else
            return this.elements[index];
    } else
        throw new Error("参数:类型错误期望类型是:number,实际传入类型为:" + typeof index);
}
/* 通过 key 返回值 */
Map.prototype.getByKey = function(key) {

    if (key && typeof key == "string" && (key + "").trim().length > 0) {
        var matchRel = "";
        this.elements.some(function(val, index) {
            if (val instanceof Object && !(val instanceof Array)) {
                if (val[key]) {
                    matchRel = val[key];
                    return true;
                }
            }
        });
        if (matchRel.length != 0)
            return matchRel;
        else
            throw new Error("there not exist value mapped by the key=>" + key
                    + " in the map");
    } else
        throw new Error("参数:类型错误期望类型是:string,实际传入类型为:" + typeof key);
}
/* 遍历Map */
Map.prototype.each = function(fn) {
    for (var i = 0; i < this.elements.length; i++) {
        fn(this.elements[i], i);
    }
}
/* 通过 index 和 count 移除值 */
Map.prototype.removeByIndex = function(index, count) {
    if (typeof index == "number") {
        if (index > this.elements.length - 1 || index < 0) {
            throw new Error("IndexOutOfBoundsException: " + index);
        } else {
            if (typeof count == "number")
                this.elements.splice(index, count);
            else if (count === undefined)
                this.elements.splice(index);
            else
                throw new Error("参数2:类型错误期望类型是:number,实际传入类型为:" + typeof count);
        }
    } else
        throw new Error("参数1:类型错误期望类型是:number,实际传入类型为:" + typeof index);
}
/* 通过 key 移除值 */
Map.prototype.removeByKey = function(key) {
    var _this = this;
    this.elements.forEach(function(val, index) {
        if (val instanceof Object && !(val instanceof Array)) {
            if (val[key]) {
                _this.elements.splice(index, 1);
            }
        }
    });
}
/* 清空Map */
Map.prototype.clear = function() {
    this.elements = [];
}
/* 判断Map是否包含元素 */
Map.prototype.isEmpty = function() {
    return this.elements.length == 0 ? true : false;
}
/* 判断Map是否包含给定的Key值 */
Map.prototype.containsKey = function(key) {
    var flag = 0;
    var _this = this;
    this.elements.some(function(val, index) {
        if (val instanceof Object && !(val instanceof Array)) {
            if (val[key]) {
                flag = 1;
                _this.indexBykey = index;
                return true;
            }
        }
    });
    return flag == 0 ? false : true;
}
/* 把Map中的元素返回为JSON格式的字符串 */
Map.prototype.toString = function() {
    
    // return JSON.stringify(this.elements).replace(new RegExp("\\[|\\]","g"),"");
    
    return JSON.stringify(this.elements).replace(/\[|\]/g, "");
}

===================使用上面封装的Map进行测试==============================

<html>
<head>
<meta charset='utf-8'/>
<meta name='Author' content="Charles Ran"/>
<script type="text/javascript" src="Map.js"></script>
<script type='text/javascript'>
  window.οnlοad=function(){
     var map=new Map();
     map.add([1,2,3]);
     map.add({"name":"CharlesRan","age":30});
     map.add([1,2,"AAA"]);

      var map2=new Map();
      map2.add({"name":"pjg","age":30});
      map2.add([1,2,"ccc"]);
    
      console.log(map);
      console.log(map2);

  }
</script>
</head>
<body>
</body>
</html>

 

 

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值