JS 字典

字典

定义: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;
    })
}
posted @ 2016-08-23 14:09  Dark_liu  阅读(308)  评论(0编辑  收藏  举报