zoukankan      html  css  js  c++  java
  • 字典数据结构与算法JavaScript描述(7)

    字典

    字典是一种以键-值对形式存储数据的数据结构。


    Dictionary 类

    Dictionary 类的基础是Array 类,而不是Object 类。

    function Dictionary( ){
        this.dataStore = []; // 后面为了给字典增加排序功能,所以此处用数组来实现存储
        this.add = add;
        this.remove = remove;
        this.find = find;
        this.showAll = showAll;
        this.count = count;
        this.clear = clear;
    }
    function add(key, value){
        this.dataStore[key] = value;
    }
    function remove(key){
        delete this.dataStore[key];
    }
    function find(key){
        return this.dataStore[key];
    }
    function showAll(){
        var dataKeys = [].prototype.slice.call(Object.keys(this.dataStore)); // 存疑:Object.keys方法的返回值本来就是数组,此处为何用借用数组的slice方法将其转为数组?
        for(var key in dataKeys){
            console.log(dataKeys[key] + ' -> ' + this.dataStore[dataKeys[key]]); // 存疑:此处写法很怪异
        }
    }
    function count(){
        var n = 0;
        for(var key in Object.keys(this.dataStore)){
            ++n;
        }
        return n;
    }
    function clear(){
        Object.keys(this.dataStore).forEach(function(key){
            delete this.dataStore[key];
        });
    }
    

    为Dictionary类添加排序功能

    字典的主要用途是通过键取值,我们无须太关心数据在字典中的实际存储顺序。然而,很多人都希望看到一个有序的字典。

    function showAll(){
        for(var key in Object.keys(this.dataStore).sort()){ // 利用数组的sort方法对键排序
            console.log(key + ' -> ' + this.dataStore[key]);
        }
    }
    
  • 相关阅读:
    分享ASP.NET+jQuery MiniUI后台购物管理
    ASP.NET发送电子邮件
    LINQ学习(三):Where子句
    ASP.NET配置KindEditor文本编辑器
    一步步写自己SqlHelper类库(五):Command对象
    ASP.NET生成静态页面的简单实现
    兼职开发悟出的点点滴滴
    设计模式学习笔记
    if else替代者
    ASP.NET 一生命周期中的额事件
  • 原文地址:https://www.cnblogs.com/clover77/p/9199686.html
Copyright © 2011-2022 走看看