Posted on 2009-06-18 16:12
oathleo 阅读(7919)
评论(3) 编辑 收藏 所属分类:
Web
js 里 Object本身可以做为Map。
条件是Key只能是String
如果要用对象做为Key,这个Map可以来实现。
效率上由于_getIndex方法每次都要遍历,耗时很长,所以通常在1:10左右
总结以上,如果Map的Key是String,最好还是用Object来实现。
而且用in来遍历Map,效率上不是网上说的那么差,和for()差不多
TWaver.Map = function(){
this._entrys = null;
this.initialize.apply(this, arguments);
}
TWaver.Map.prototype = {
initialize: function(){
this._entrys = new Array();
},
put: function(key, value){
if (key == null || key == undefined) {
return;
}
var index = this._getIndex(key);
if (index == -1) {
var entry = new Object();
entry.key = key;
entry.value = value;
this._entrys[this._entrys.length] = entry;
}else{
this._entrys[index].value = value;
}
},
get: function(key){
var index = this._getIndex(key);
return (index != -1) ? this._entrys[index].value : null;
},
remove: function(key){
var index = this._getIndex(key);
if (index != -1) {
this._entrys.splice(index, 1);
}
},
clear: function(){
this._entrys.length = 0;;
},
contains: function(key){
var index = this._getIndex(key);
return (index != -1) ? true : false;
},
getCount: function(){
return this._entrys.length;
},
getEntrys: function(){
return this._entrys;
},
_getIndex: function(key){
if (key == null || key == undefined) {
return -1;
}
var _length = this._entrys.length;
for (var i = 0; i < _length; i++) {
var entry = this._entrys[i];
if (entry == null || entry == undefined) {
continue;
}
if (entry.key === key) {//equal
return i;
}
}
return -1;
}
}