亲宝软件园·资讯

展开

Javascript实现的Map集合工具类完整实例

akwolf 人气:0

本文实例讲述了Javascript实现的Map集合工具类。分享给大家供大家参考。具体如下:

var Map = function(){
  // 构造entry实体
  var Entry = function(key, value){
    this.key = key;
    this.value = value;
  }
  this.entries = new Array();
  // 构造put方法在数组中放入一个Entry
  this.put = function(key, value){
    // 数组中已存在就不放入
    for (var i = 0; i < this.size(); i++) {
      if (this.entries[i].key === key) {
        return false;
      }
    }
    this.entries.push(new Entry(key, value));
  };
  // 模拟get方法
  this.get = function(key){
    for (var i = 0; i < this.size(); i++) {
      if (this.entries[i].key === key) {
        return this.entries[i].value;
      }
    }
    return null;
  };
  // 查找下标值
  this.indexOf = function(key){
    var index = -1;
    for (var i = 0; i < this.size(); i++) {
      if (this.entries[i].key === key) {
        index = i;
        break;
      }
    }
    return index;
  }
  // 删除一个元素
  this.remove = function(key){
    var index = this.indexOf(key);
    if (index != -1) {
      this.entries.splice(index, 1);
    }
  }
  // 取得map长度
  this.size = function(){
    return this.entries.length;
  };
  // 重新设置键值对
  this.setValue = function(key, value){
    var index = this.indexOf(key);
    if (index != -1) {
      this.entries[i].value = value;
    };
  };
  // 是否为空map
  this.isEmpty = function(){
    return this.size() <= 0;
  };
  //清空map ;
  this.clear = function(){
    this.entries = [];
  };
  // 得到entry实体
  this.getEntry = function(index){
    if (index >= 0 && index < this.size()) {
      return this.entries[index];
    }
    return null;
  }
  this.toString = function(){
    var str = "[";
    for (var i = 0; i < this.size(); i++) {
      str += this.getEntry(i).key + "=" + this.getEntry(i).value + ",";
    }
    // 去除最后一个","
    str = str.substring(0, str.length - 1);
    str += "]";
    return str;
  };
}

希望本文所述对大家的javascript程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论