码迷,mamicode.com
首页 > 编程语言 > 详细

javascript版的HashMap

时间:2017-06-21 14:08:50      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:amp   contain   array   json   func   remove   asc   move   java   

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

标签:amp   contain   array   json   func   remove   asc   move   java   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!