首页 > 编程语言 > 详细

数据结构与算法之字典

时间:2019-06-15 12:38:39      阅读:146      评论:0      收藏:0      [点我收藏+]

字典

基于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];
        }
    }
}

数据结构与算法之字典

原文:https://www.cnblogs.com/simpul/p/11027172.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!