JavaScript 字典(Dictionary)数据结构实现详解

作者:纸飞机时间:2026-10-30 22:47:50浏览:167

本文基于《数据结构与算法--javascript描述》一书,详细讲解如何在 JavaScript 中手动实现字典(Dictionary)数据结构。文章介绍了使用裸对象作为底层存储的方案,对比了通过变量跟踪与实时计算两种获取字典长度的方法,并提供了完整的源代码实现及 GitHub、OSChina 仓库地址,供开发者参考复用。

背景

近期在阅读《数据结构与算法--javascript描述》一书,并在 npmjs.org 上搜索相关库以寻找合适的参考实现。由于未找到完全符合个人需求的现有库,决定自行逐一实现这些数据结构,以便未来使用时能够直接调用。

设计思路

采用裸对象(datastore)作为底层元素存储容器。

提供了两种获取字典长度的方式:一是通过内部变量进行跟踪记录,二是通过遍历实时计算。

具体实现

(function(){
    "use strict";
    function Dictionary(){
        this._size = 0;
        this.datastore = Object.create(null);
    }
    Dictionary.prototype.isEmpty = function(){
        return this._size === 0;
    };
    Dictionary.prototype.size = function(){
        return this._size;
    };
    Dictionary.prototype.clear = function(){
        for(var key in this.datastore){
            delete this.datastore[key];
        }
        this._size = 0;
    };
    Dictionary.prototype.add = function(key, value){
        this.datastore[key] = value;
        this._size++;
    };
    Dictionary.prototype.find = function(key){
        return this.datastore[key];
    };
    Dictionary.prototype.count = function(){
        var n = 0;
        for(var key in this.datastore){
            n++;
        }
        return n;
    };
    Dictionary.prototype.remove = function(key){
        delete this.datastore[key];
        this._size--;
    };
    Dictionary.prototype.showAll = function(){
        for(var key in this.datastore){
            console.log(key + "->" + this.datastore[key]);
        }
    };
    module.exports = Dictionary;
})();

代码托管地址

https://github.com/zhoutk/js-data-struct

http://git.oschina.net/zhoutk/jsDataStructs

以上为 JavaScript 字典(Dictionary)基础实现的详细内容,如需了解更多关于 JavaScript 字典 Dictionary 的资料,请查阅本站其他相关文章。

作者最新文章