JavaScript实现Map数据结构

function Map(){
this.map = new Object();
this.length = 0;

this.size = function(){
return this.length;
}

this.put = function(key, value){

if( !this.map['_' + key])
{
++this.length;
}

this.map['_' + key] = value;

}

this.remove = function(key){

if(this.map['_' + key])
{

--this.length;
return delete this.map['_' + key];
}
else
{
return false;
}
}

this.containsKey = function(key){

return this.map['_' + key] ? true:false;

}

this.get = function(key){

return this.map['_' + key] ? this.map['_' + key]:null;

}


this.inspect=function(){
var str = '';

for(var each in this.map)
{
str+= '\n'+ each + ' Value:'+ this.map[each];
}

return str;
}

}

------------------------------------------
测试程序

//测试Map的调用方法

function testMap(){
var testmap=new Map();
alert("cur size:" + testmap.size());
alert("get bu cunzai:" + testmap.get("bu cunzai"));
testmap.put("01","michael");
testmap.put("01","michael1");
testmap.put("01","michael11");
testmap.put("01","michael1111");
testmap.put("011","michael1111");
testmap.put("object",new Array());
testmap.put("number",1234);
testmap.put(78944444444444444422222222222222,1234);
testmap.put("function",function(num){return num;});

//alert("function:"+ testmap.get("function")(789));
alert("function:"+ testmap.get("function")(78944444444444444422222222222222));
alert ("cur size:" + testmap.size() + "inspect:" + testmap.inspect());
alert("remove function:" + testmap.remove("function"));
alert("remove object:" + testmap.remove("object"));
testmap.put("02","michael2");
testmap.put("022","achang2");
testmap.put("022","achang3");
alert ("cur size:" + testmap.size() + "inspect:" + testmap.inspect());


var key="02"

if (testmap.containsKey(key)){
var value=testmap.get(key);
alert ("02 first|"+value);
}else{
alert("no Cotain" + key);
}

alert("remove:" + testmap.remove("02"));
alert("cur size:" + testmap.size());
alert( testmap.remove("0000002"));
alert("cur size:" + testmap.size());
alert("contain:" + testmap.containsKey("0000002"));

if (testmap.containsKey(key)){
var value=testmap.get(key);
alert ("02 |"+ value);
}else{
alert ("no Contain:"+key);
}



}
testMap();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值