美文网首页javascript
js实现Hashmap功能

js实现Hashmap功能

作者: 风一样的存在 | 来源:发表于2019-01-13 20:06 被阅读0次

    js并没有类似Java的键值对存储集合类,但是可以自己定义实现:

    function HashMap() {
        this.map = {};
    }
    HashMap.prototype = {
        put: function (key, value) {// 向Map中增加元素(key, value) 
            this.map[key] = value;
        },
        get: function (key) { //获取指定Key的元素值Value,失败返回Null 
            if (this.map.hasOwnProperty(key)) {
                return this.map[key];
            }
            return null;
        },
        remove: function (key) { // 删除指定Key的元素,成功返回True,失败返回False
            if (this.map.hasOwnProperty(key)) {
                return delete this.map[key];
            }
            return false;
        },
        removeAll: function () {  //清空HashMap所有元素
            this.map = {};
        },
        keySet: function () { //获取Map中所有KEY的数组(Array) 
            var _keys = [];
            for (var i in this.map) {
                _keys.push(i);
            }
            return _keys;
        }
    };
    HashMap.prototype.constructor = HashMap;
    

    使用方法:


    hashmap.png

    相关文章

      网友评论

        本文标题:js实现Hashmap功能

        本文链接:https://www.haomeiwen.com/subject/rrvldqtx.html