【JavaScript数据结构与算法】字典

字典

字典是一种以键-值对形式存储数据的数据结构。JavaScript的Object类就是以字典的方式设计的,此处将使用Object类本身的特性,实现一个Dictionary类。

1 Dictionary类

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

function Dictionary(){
    this.datastore=new Array();
    this.add=add;
    this.find=find;
    this.remove=remove;
    this.showAll=showAll;
}
//增加元素 接收两个参数:键和值
function add(key,value){
    this.datastore[key]=value;
}
//以键为参数返回和其关联的值
function find(key){
    return this.datastore[key];
}
//使用js内置函数delete,该函数是Object类的一部分,使用键的引用作为参数,同时删除键和与其关联的值。
function remove(key){
    delete this.datastore[key];
}
//显示字典中所有的键-值对
function showAll() {
    for(key in this.datastore){
        console.log(key+"->"+this.datastore[key]);
    }
    //或者
        Object.keys(this.datastore).forEach(element=>{
        console.log(element+"->"+this.datastore[element]);
    });
}

在这里插入图片描述

2 Dictionary类的辅助方法

  1. 返回字典中的元素个数
function count() {
    var n = 0;
    for(key in this.datastore){
        ++n;
    }
    //或者
     Object.keys(this.datastore).forEach(element=>{
        ++n;
    });
    return n;
}

注意:这里为什么不使用length属性?

  • 当键的类型为字符串时,length属性就不管用了。
var nums=new Array();
nums[0]=1;
nums[1]=2;
console.log(nums.length);//2
var pbook=new Array();
pbook["David"]=1;
pbook["Jennifer"]=2;
console.log(pbook.length);//0
  1. 清空字典中的元素
function clear() {
    for(key in this.datastore){
        delete this.datastore[key];
    }
    //或者
    Object.keys(this.datastore).forEach(element=>{
        delete this.datastore[element];
    });
}

3 为Dictionary类添加排序功能

数组本身是可以通过sort()方法排序的,但对于字符串作为键的情况无效。

function showAll(){
   Object.keys(this.datastore).sort().forEach(element=>
       {
          console.log(element+"->"+this.datastore[element]);
       });
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值