• 字典是一种以键值对形式存在的数据格式,即[key]: value,在JS中可以很简单的使用Object类来实现字典。

    实现一个字典

    首先定义一个Dictionary类

    function Dictionary() {
      this.data = new Array();
    }
    

    在Dictionary类中要使用数组来进行储存,这样一来,数组的索引即为key值。

    然后定义一些基本方法

    添加键值

    function add(key, value) {
      this.data[key] = value;
    }
    

    查询值

    function find(key) {
      return this.data[key];
    }
    

    删除值

    function remove(key) {
      delete this.data[key];
    }
    

    返回字典长度

    function count() {
      var n = 0;
      for (key in this.data) {
        ++n;
      }
      return(n);
    }
    

    输出所有值

    function returnAll() {
      for(let key in Object.keys(this.data)) {
        return(key + ":" + this.data[key]);
      }
    }
    

    对字典排序

    可以使用原生的sort()对数组进行排序。

    function returnAll() {
      for(let key in Object.keys(this.data).sort()) {
        return(key + ":" + this.data[key]);
      }
    }
    

    清空所有值

    function clear() {
      for (key in this.data) {
        delete this.data[key];
      }
    }
    

    完整代码

    function Dictionary() {
      this.data = new Array();
      this.add = add;
      this.find = find;
      this.remove = remove;
      this.count = count;
      this.returnAll = returnAll;
      this.clear = clear;
    }
    function add(key, value) {
      this.data[key] = value;
    }
    function find(key) {
      return this.data[key];
    }
    function remove(key) {
      delete this.data[key];
    }
    function count() {
      var n = 0;
      for (key in this.data) {
        ++n;
      }
      return(n);
    }
    function returnAll() {
      for (key in this.data) {
        alert(key + " :" + this.data[key]);
      }
    }
    function clear() {
      for (key in this.data) {
        delete this.data[key];
      }
    }