用Javascript中模拟Java中的Map



用js模拟实现Map,代码如下:

 

[javascript] view plain copy print ?
  1. var Map = function(){  
  2.     var Entry = function(key, value){  
  3.         this.key = key;  
  4.         this.value = value;  
  5.     };  
  6.     this.entries = new Array();  
  7.     this.put = function(key, value){  
  8.         for (var i = 0; i < this.entries.length; i++) {  
  9.             if (this.entries[i].key === key) {  
  10.                 return false;  
  11.             }  
  12.         }  
  13.         this.entries.push(new Entry(key, value));  
  14.         return true;  
  15.     };  
  16.     this.get = function(key){  
  17.         for (var i = 0; i < this.entries.length; i++) {  
  18.             if (this.entries[i].key === key) {  
  19.                 return this.entries[i].value;  
  20.             }  
  21.         }  
  22.         return null;  
  23.     };  
  24.     this.remove = function(key) {  
  25.         var index = this.indexOf(key);  
  26.         if(index != -1) {  
  27.             this.entries.splice(index,1);  
  28.         }  
  29.     };  
  30.     this.setValue = function(key, value) {  
  31.         var index = this.indexOf(key);  
  32.         if(index != -1) {  
  33.             this.entries[index].value = value;  
  34.         }  
  35.     };  
  36.     this.getEntry = function(index) {  
  37.         if(index >= 0 && index < this.size()) {  
  38.             return this.entries[index];  
  39.         }  
  40.         return null;  
  41.     };  
  42.     this.size = function(){  
  43.         return this.entries.length;  
  44.     };  
  45.     this.isEmpty = function(){  
  46.         return this.entries.length <= 0;  
  47.     };  
  48.     this.clear = function() {  
  49.         this.entries = [];  
  50.     };  
  51.     this.indexOf = function(key) {  
  52.         var index = -1;  
  53.         for(var i=0; i<this.size(); i++) {  
  54.             if(key == this.entries[i].key) {  
  55.                 index = i;  
  56.                 break;  
  57.             }  
  58.         }  
  59.         return index;  
  60.     };  
  61.     this.toString = function() {  
  62.         var str = '[';  
  63.         for(var i=0; i<this.size(); i++) {  
  64.             str += (this.entries[i].key + '='   
  65.                 + this.entries[i].value + ',')  
  66.         }  
  67.         str = str.substr(0, str.length-1);  
  68.         str += ']';  
  69.         return str;  
  70.     };  
  71. }  

 

 

在网上找了,发现remove方法的实现,基本上不是用splice,而是用unshift,经过简单测试,好像splice的效率更高。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值