Home > Web Front-end > JS Tutorial > body text

Complete example of Map collection tool class implemented in Javascript_javascript skills

WBOY
Release: 2016-05-16 15:47:59
Original
1069 people have browsed it

The example in this article describes the Map collection tool class implemented by Javascript. Share it with everyone for your reference. The details are as follows:

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;
  };
}

Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!