zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    SQL Server 实现Split函数
    15.java设计模式之访问者模式
    14.java设计模式之命令模式
    13.java设计模式之模板模式
    12.java设计模式之代理模式
    11.java设计模式之享元模式
    10.java设计模式之外观模式
    9.java设计模式之组合模式
    8.java设计模式之装饰者模式
    7.java设计模式之桥接模式
  • 原文地址:https://www.cnblogs.com/duanqiao123/p/11941101.html
Copyright © 2011-2022 走看看