DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> Javascript實現的Map集合工具類完整實例
Javascript實現的Map集合工具類完整實例
編輯:關於JavaScript     

本文實例講述了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程序設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved