数据结构与算法之字典

字典

基于Array类构造一个字典类用于储存键值对(之前一直不知道JS的Array原来可以存储键值对,第一次看到简直惊呆了)

暂时看到的内容挺简单的,不明白这个的存在意义是什么,感觉还不如直接用JSON来得直接。
直接上代码不解释。

//定义字典类
function Dictionary(){
    this.datastore = new Array();
}
Dictionary.prototype = {
    constructor: Dictionary,
    add(key, value){
        this.datastore[key] = value;
    },
    find(key){
        return this.datastore[key];
    },
    remove(key){
        delete this.datastore[key];
    },
    showAll(){
        for(var key of Object.keys(this.datastore).sort()){
            console.log(key + " : " + this.datastore[key]);
        }
    },
    //由于Array在存储键值对时,length属性失真(==0),因此需要重新定义一个函数计算元素个数
    count(){
        return Object.keys(this.datastore).length;
    },
    clear(){
        for(var key of Object.keys(this.datastore)){
            delete this.datastore[key];
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/simpul/p/11027172.html