JS实现类拟JAVA中MAP对像的功能

15 篇文章 0 订阅
/*
name:    Map.js
author:  WindDC
date:    2006-10-27
content: 本程序用JS实现类拟JAVA中MAP对像的功能
*/
function Node(key,value){//键值对对象
this.key=key;
this.value=value;
}

function Map(){//Map类
this.nodes=new Array();
}

Map.prototype.put=function(key,value){//往容器中加入一个键值对
for(var i=0;i<this.nodes.length;i++)
if(this.nodes[i].key==key){//如果键值已存在,则put方法为更新已有数据
this.nodes[i].value=value;
return;
}
var node=new Node(key,value);
this.nodes.push(node);
return;
}//put
   
Map.prototype.get=function(key){//获取指定键的值
for(var i=0;i<this.nodes.length;i++)
if(this.nodes[i].key==key)
return this.nodes[i].value;
return null;
}//get

Map.prototype.size=function(){//获取容器中对象的个数
return this.nodes.length;
}//size
         
Map.prototype.clear=function(){//清空容器
while(this.nodes.length>0)
this.nodes.pop();      
}//clear

Map.prototype.remove=function(key){//删除指定值
for(var i=0;i<this.nodes.length;i++)
if(this.nodes[i].key==key){
	var newNodes= new Array() ;
	 if(i>0){   
	    newNodes = newNodes.concat(this.nodes.slice(0,i),this.nodes.slice(i+1));
	  }
	else//删除的是第一个元素
		{ 
		   newNodes=this.nodes.slice(1);
		}
		
	this.nodes=newNodes;

}
}//remove


Map.prototype.isEmpty=function(){//是否为空
if(this.nodes.length==0)
return true;
else
return false;
}//isEmpty

Map.prototype.toString=function(){
var str="[";
for(var i=0;i<this.nodes.length;i++){
if(i<this.nodes.length-1)
str=str+this.nodes[i].key+",";
else
str=str+this.nodes[i].key;    
}
str=str+"]";
return str;
}//toString

Map.prototype.toJson=function(){
	var sjson="[";
	for(var i=0;i<this.nodes.length;i++){
		if(i<this.nodes.length-1)
			sjson+="{\""+findObjKV(this.nodes[i].value)+"\"},";
		else
			sjson+="{\""+findObjKV(this.nodes[i].value)+"\"}";  
	}
	sjson+="]";
	return sjson;
}//toJson

Map.prototype.indexOf = function(i){
	return this.nodes[i];
}

//遍历对象key val
function findObjKV(source){
	var result=new Array();
	for(k in source){
		if(source.hasOwnProperty(k)){
			result.push("\""+k+"\":\""+source[k]+"\"");
		}
	}
	return result.join(",");
}

 使用:

var conditionMap = new Map();
conditionMap.put(k,v);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值