JS Map

来源:互联网 发布:silverlight mac 编辑:程序博客网 时间:2024/04/24 14:14
/**
 * 模拟java HashMap
 * @author king
 **/
function Map(){
    this.keys = new Array();
    this.values = new Array();
}

/**
 * 将元素放入Map
 * @param key
 * @param value
 * @author king
 **/
Map.prototype.put = function(key,value){
    if(!key){return ;}
    if(!value){return;}
    var i = eval("this.KeyIndex_" + key);
    if(i == undefined){
        i = this.keys.length;
        eval("this.KeyIndex_" + key +" = i;");
    }
    if(i >= 0 && i < this.values.length){
           this.values[i] = value;
    } else {
        this.keys[this.values.length] = key;
        this.values[this.values.length] = value;
    }
}

/**
 * 得到键值为key的元素
 * @param key
 * @author king
 **/
Map.prototype.get = function (key){
    var i = eval("this.KeyIndex_" + key);
    if(i == undefined){
        return "";
    }
    if(i >= 0 && i < this.values.length){
           return this.values[i]==null?"":this.values[i];
    }
    return "";
}

/**
 * 从Map中删除键值为key元素
 * @param key
 * @author king
 **/
Map.prototype.remove = function (key){
    var i = eval("this.KeyIndex_" + key);
    if(i == undefined){
        return ;
    }
    if(i >= 0 && i < this.values.length){
        eval("this.KeyIndex_" + key+"=undefined;");
           this.keys[i] = "";
        this.values[i] = "";
    }
    setTimeout("CollectGarbage();",1500);
}

/**
 *删除所有对象引用
 *@author king
 */
Map.prototype.removeAll = function (){
    for(i=0;i<this.values.length;i++){
        eval("this.KeyIndex_" + this.keys[i] +" = undefined;");
        this.keys.splice(i,1);
        this.values.splice(i,1);
    }
}

/**
 * 得到Map的大小
 * @author king
 **/
Map.prototype.size = function (){
    return this.keys.length;
}

原创粉丝点击