JS自定义 Map
<script>
function HashMap(){this.map = {};}
HashMap.prototype = {
put : function(key, value){ this.map[key] = value;},
get : function(key){
if(this.map.hasOwnProperty(key)){ return this.map[key];}
return null;
},
remove : function(key){
if(this.map.hasOwnProperty(key)){ return delete this.map[key];}
return false;
},
removeAll : function(){this.map = {};},
keySet : function(){
var _keys = [];
for(var i in this.map){
_keys.push(i);
}
return _keys;
}
};
HashMap.prototype.constructor = HashMap;
//排序方法
function compare(val1,val2) {
// 转换为拼音
//val1 = Pinyin.getFullChars(val1).toLowerCase();
//val2 = Pinyin.getFullChars(val2).toLowerCase();
// 获取较长的拼音的长度
var length = val1.length > val2.length ? val1.length:val2.length;
// 依次比较字母的unicode码,相等时返回0,小于时返回-1,大于时返回1
for(var i = 0; i < length; i++ ){
var tmp_val1 = isNaN(val1.charCodeAt(i)) ? 0:val1.charCodeAt(i);
var tmp_val2 = isNaN(val2.charCodeAt(i)) ? 0:val2.charCodeAt(i);
var differ = tmp_val1 - tmp_val2;
//console.log(tmp_val1+" "+tmp_val2);
//console.log(differ);
if(differ == 0) {
continue;
}else {
//if(val1.charAt(i) == '_' ) {
//return -1;
//}
return differ;
}
}
//if(i == length) {
// return val1.length - val2.length;
//}
}
//init map
var hashMap = new HashMap();
//add value
hashMap.put('key111' ,'value1');
hashMap.put('key3' ,'value3');
hashMap.put('key' ,'value2');
hashMap.put('aa' ,'value2');
hashMap.put('bbbbbb' ,'value2');
var hash_keyset = hashMap.keySet();
for(var i=0; i<hash_keyset.length; i++){
var key = hash_keyset.sort(compare)[i];//key排序
//var key = hash_keyset[i];//不排序
//alert(key+" "+hashMap.get(key));
console.log(key+" "+hashMap.get(key));
}
</script>
出处附录: