HashMap代码(这种实现方式是错误的,错误原因:代码中_map、_length变量是HashMap的所有实例共用的):

/**
 * HashMap
 * 2021年09月09日
 */

(function (global) {
    var _map;
    var _length;

    global.HashMap = function () {
        _map = {};
        _length = 0;
    };

    global.HashMap.prototype = {
        put: function (key, value) {
            if (!_map.hasOwnProperty(key)) {
                _length++;
            }
            _map[key] = value;
        },

        get: function (key) {
            if (_map.hasOwnProperty(key)) {
                return _map[key];
            }
            return null;
        },

        containsKey: function (key) {
            return _map.hasOwnProperty(key);
        },

        size: function () {
            return _length;
        },

        remove: function (key) {
            if (_map.hasOwnProperty(key)) {
                _length--;
                return delete _map[key];
            }
            return false;
        },

        removeAll: function () {
            _map = {};
        },

        keys: function () {
            var keys = [];
            for (var item in _map) {
                keys.push(item);
            }
            return keys;
        },

        values: function () {
            var values = [];
            for (var item in _map) {
                values.push(_map[item]);
            }
            return values;
        }
    };

    global.HashMap.prototype.constructor = global.HashMap;

})(window);
View Code

相关文章:

  • 2021-06-11
  • 2021-10-24
  • 2021-04-17
  • 2021-09-29
  • 2022-01-16
  • 2021-08-14
  • 2021-07-07
  • 2021-11-12
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-25
  • 2021-04-19
  • 2021-06-12
  • 2021-12-10
相关资源
相似解决方案