js模拟HashMap的存储结构-无序版

function Map(key,value){
this[key] = value;

Map.prototype.put = function(key,value){
delete key;
this[key] = value;
}
Map.prototype.get = function(key){
return this[key];
}
//如果 Map 包含指定键的映射,则返回 true
Map.prototype.containsKey = function(key){
return this.hasOwnProperty(key);
}

//从 Map 中删除键和关联的值 删除成功返回true否则返回false
Map.prototype.remove = function(key){
return delete this[key];
}

//从 Map 中删除所有映射
Map.prototype.clear = function(){
for(var property in this){
delete this[property];
}
return this;
}

//返回所有的Key  字符串数组的形式
Map.prototype.keySet = function(){
var keyArray = new Array();
for(var property in this){
keyArray.push(property);
}
return keyArray;
}

//返回所有的Key对应的数据,数组形式
Map.prototype.entrySet = function(){
var valueArray = new Array();
for(var property in this){
if(this.hasOwnProperty(property)){
valueArray.push(this[property]);
}
}
return valueArray;
}


//返回 Map 中的键-值映射的数目
Map.prototype.size = function(){
var count = 0;
for(var property in this){
if(this.hasOwnProperty(property)){
++count;
}
}
return count;
}

//如果 Map 不包含键-值映射,则返回 true
Map.prototype.isEmpty = function(){
if(this.size > 0){
return true;
}
return false;
}

}



测试代码:

var map = new Map("key1","key1");


console.log(map.get("key1"));


map.put("key2","key2")
console.log(map.get("key2"));


map.put("key2","改过后的key2");
console.log(map.get("key2"));


console.log("size:"+map.size());
console.log("keySet:"+map.keySet());
console.log("entrySet:"+map.entrySet());
console.log("keySet:"+map.isEmpty());
console.log("remove:"+map.remove("key11"));
console.log("getkey1:"+map.get("key1"));
console.log("删除key1后:"+map.size());


console.log("包含containsKey:"+map.containsKey("key1"));
console.log("不包含containsKey:"+map.containsKey("key111"));


//console.log("clear:"+map.clear());
//console.log("清除后size:"+map.size());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值