JS自定义 Map

Posted 段桥123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>

出处附录:

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

以上是关于JS自定义 Map的主要内容,如果未能解决你的问题,请参考以下文章

Js自定义数组map之bigmap

javascript-自定义Map

js Array 创建具有自定义初始值的数组

如何将 flyto 传单功能添加到自定义 Svg 地图

LeetCode 791 自定义字符串排序[Map 自定义排序] HERODING的LeetCode之路

js json转xml(可自定义属性,区分大小写)