JS 字典

旧时模样 提交于 2020-01-12 20:52:55

字典

定义:Dictionary 类的基础是Array类

抽象实现

  • 一个存放数据的集合Array
  • 新增 Add
  • 删除 remove
  • 包含 contains

代码实现

function Dictionary() {
    this.dataStore = [];
    this.add = add;
    this.remove = remove;
    this.display = display;
    this.count = count;
    this.contains = contains;
}

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

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

function count() {
    var num = 0;
    Object.keys(this.dataStore).forEach(function (key) {
        num++;
    });
    return num;
}

function display() {
    var data = this.dataStore
    var strHtml = Object.keys(data).sort().map(function (key) {
        return "key:" + key + ",value:" + data[key];
    }).join("|")
    return strHtml;
}

function contains(key) {
    return Object.keys(this.dataStore).some(function (keyName) {
        return keyName == key;
    })
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!