码迷,mamicode.com
首页 > Web开发 > 详细

JS自定义 Map

时间:2019-11-27 12:40:24      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:LLC   nic   unicode   定义   获取   rop   put   case   continue   

<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>

出处附录:

https://www.cnblogs.com/songfei90/p/10523229.html

JS自定义 Map

标签:LLC   nic   unicode   定义   获取   rop   put   case   continue   

原文地址:https://www.cnblogs.com/duanqiao123/p/11941101.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!