欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS模擬的Map類實現(xiàn)方法

 更新時間:2016年06月17日 09:25:03   作者:hbiao68  
這篇文章主要介紹了JS模擬的Map類實現(xiàn)方法,可實現(xiàn)模擬java中map屬性按照鍵值對保存的功能,提供了采用數(shù)組和json兩種實現(xiàn)方式,需要的朋友可以參考下

本文實例講述了JS模擬的Map類。分享給大家供大家參考,具體如下:

根據(jù)java中map的屬性,實現(xiàn)key----value保存

1、使用數(shù)組方式存儲數(shù)據(jù),(使用閉包)

function Map() {
  var struct = function (key, value) {
    this.key = key;
    this.value = value;
  }
  var put = function (key, value) {
    for (var i = 0; i < this.arr.length; i++) {
      if (this.arr[i].key === key) {
        this.arr[i].value = value;
        return;
      }
    }
    this.arr[this.arr.length] = new struct(key, value);
  }
  var get = function (key) {
    for (var i = 0; i < this.arr.length; i++) {
      if (this.arr[i].key === key) {
        return this.arr[i].value;
      }
    }
    return null;
  }
  var remove = function (key) {
    var v;
    for (var i = 0; i < this.arr.length; i++) {
      v = this.arr.pop();
      if (v.key === key) {
        continue;
      }
      this.arr.unshift(v);
    }
  }
  var size = function () {
    return this.arr.length;
  }
  var isEmpty = function () {
    return this.arr.length <= 0;
  }
  this.arr = new Array();
  this.get = get;
  this.put = put;
  this.remove = remove;
  this.size = size;
  this.isEmpty = isEmpty;
}

2、使用JSON方式存儲數(shù)據(jù)(使用原型方式拓展方法)

function Map() {
  this.obj = {};
  this.count = 0;
}
Map.prototype.put = function (key, value) {
  var oldValue = this.obj[key];
  if (oldValue == undefined) {
    this.count++;
  }
  this.obj[key] = value;
}
Map.prototype.get = function (key) {
  return this.obj[key];
}
Map.prototype.remove = function (key) {
  var oldValue = this.obj[key];
  if (oldValue != undefined) {
    this.count--;
    delete this.obj[key];
  }
}
Map.prototype.size = function () {
  return this.count;
}
var map = new Map();
map.put("key","map");
map.put("key","map1");
alert(map.get("key"));//map1
map.remove("key");
alert(map.get("key"));//undefined

更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數(shù)據(jù)結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數(shù)學運算用法總結

希望本文所述對大家JavaScript程序設計有所幫助。

相關文章

最新評論