1 <script> 2 function HashMap(){this.map = {};} 3 HashMap.prototype = { 4 put : function(key, value){ this.map[key] = value;}, 5 get : function(key){ 6 if(this.map.hasOwnProperty(key)){ return this.map[key];} 7 return null; 8 }, 9 remove : function(key){ 10 if(this.map.hasOwnProperty(key)){ return delete this.map[key];} 11 return false; 12 }, 13 removeAll : function(){this.map = {};}, 14 keySet : function(){ 15 var _keys = []; 16 for(var i in this.map){ 17 _keys.push(i); 18 } 19 return _keys; 20 } 21 }; 22 23 HashMap.prototype.constructor = HashMap; 24 25 //排序方法 26 function compare(val1,val2) { 27 // 转换为拼音 28 //val1 = Pinyin.getFullChars(val1).toLowerCase(); 29 //val2 = Pinyin.getFullChars(val2).toLowerCase(); 30 31 // 获取较长的拼音的长度 32 var length = val1.length > val2.length ? val1.length:val2.length; 33 34 // 依次比较字母的unicode码,相等时返回0,小于时返回-1,大于时返回1 35 for(var i = 0; i < length; i++ ){ 36 var tmp_val1 = isNaN(val1.charCodeAt(i)) ? 0:val1.charCodeAt(i); 37 var tmp_val2 = isNaN(val2.charCodeAt(i)) ? 0:val2.charCodeAt(i); 38 var differ = tmp_val1 - tmp_val2; 39 //console.log(tmp_val1+" "+tmp_val2); 40 //console.log(differ); 41 if(differ == 0) { 42 continue; 43 }else { 44 //if(val1.charAt(i) == '_' ) { 45 //return -1; 46 //} 47 return differ; 48 } 49 } 50 //if(i == length) { 51 // return val1.length - val2.length; 52 //} 53 } 54 //init map 55 var hashMap = new HashMap(); 56 //add value 57 hashMap.put('key111' ,'value1'); 58 hashMap.put('key3' ,'value3'); 59 hashMap.put('key' ,'value2'); 60 hashMap.put('aa' ,'value2'); 61 hashMap.put('bbbbbb' ,'value2'); 62 63 var hash_keyset = hashMap.keySet(); 64 for(var i=0; i<hash_keyset.length; i++){ 65 66 var key = hash_keyset.sort(compare)[i];//key排序 67 //var key = hash_keyset[i];//不排序 68 //alert(key+" "+hashMap.get(key)); 69 console.log(key+" "+hashMap.get(key)); 70 71 } 72 </script>
转载于:https://www.cnblogs.com/songfei90/p/10523229.html