Javascript实现Map集合工具类

本文详细介绍了如何通过JavaScript创建并操作一个变量映射(字典),包括添加、获取、删除元素以及查找和重置键值对等基本操作。


var Map = function(){
    // 构造entry实体
    var Entry = function(key, value){
        this.key = key;
        this.value = value;
    }
    
    this.entries = new Array();
    // 构造put方法在数组中放入一个Entry
    this.put = function(key, value){
        // 数组中已存在就不放入
        for (var i = 0; i < this.size(); i++) {
            if (this.entries[i].key === key) {
                return false;
            }
        }
        this.entries.push(new Entry(key, value));
    };
    // 模拟get方法
    this.get = function(key){
        for (var i = 0; i < this.size(); i++) {
            if (this.entries[i].key === key) {
                return this.entries[i].value;
            }
        }
        return null;
    };
    
    // 查找下标值
    this.indexOf = function(key){
        var index = -1;
        for (var i = 0; i < this.size(); i++) {
            if (this.entries[i].key === key) {
                index = i;
                break;
            }
        }
        return index;
    }
    // 删除一个元素
    this.remove = function(key){
        var index = this.indexOf(key);
        if (index != -1) {
            this.entries.splice(index, 1);
        }
    }
    // 取得map长度
    this.size = function(){
        return this.entries.length;
    };
    
    // 重新设置键值对
    this.setValue = function(key, value){
        var index = this.indexOf(key);
        if (index != -1) {
            this.entries[i].value = value;
        };
    };
    
    // 是否为空map
    this.isEmpty = function(){
        return this.size() <= 0;
    };
    
    //清空map ;
    this.clear = function(){
        this.entries = [];
    };
    
    // 得到entry实体
    this.getEntry = function(index){
        if (index >= 0 && index < this.size()) {
            return this.entries[index];
        }
        return null;
    }
    
    this.toString = function(){
        var str = "[";
        for (var i = 0; i < this.size(); i++) {
            str += this.getEntry(i).key + "=" + this.getEntry(i).value + ",";
        }
        // 去除最后一个","
        str = str.substring(0, str.length - 1);
        str += "]";
        return str;
    };
}


原文出去:http://blog.youkuaiyun.com/hymer2011/article/details/6259979


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值