首页 > 编程语言 > 详细

javascript版的HashMap

时间:2017-06-21 13:00:37      阅读:224      评论:0      收藏:0      [点我收藏+]

function HashMap() {
  var length = 0;
  var obj = new Object();
  this.isEmpty = function () {
    return length == 0;
  };
  this.containsKey = function (key) {
    return (key) ? (key in obj)  : false;
  };
  this.containsValue = function (value) {
    for (key in obj) {
      if (obj[key] == value) {
        return true;
      }
    }
    return false;
  };
  this.get = function (key) {
    return (this.containsKey(key)) ? obj[key] : null;
  };
  this.remove = function (key) {
    if (this.containsKey(key) && delete obj[key]) {
      length--;
    }
  };
  this.put = function (key, value) {
    if (!this.containsKey(key)) {
      length++;
    }
    obj[key] = value;
  };
  this.values = function () {
    var _values = new Array();
    for (key in obj) {
      _values.push(obj[key]);
    }
    return _values;
  };
  this.keySet = function () {
    var ks = new Array();
    for (key in obj) {
      ks.push(key);
    }
    return ks;
  };
  this.size = function () {
    return this.length;
  };
  this.clear = function () {
    this.length = 0;
    this.obj = new Object();
  };
  this.toJSON = function () {
    return JSON.stringify(obj,null,2);
  }
};

使用方法如下:

      var map = new HashMap();
      map.put(“key”, 1);
      map.remove("key");

 

javascript版的HashMap

原文:http://www.cnblogs.com/mylingc/p/7058438.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!