javascript实现字典数据结构

本文介绍了一种自定义字典类的实现方法,通过JavaScript实现了添加、删除、显示键值对等功能,并提供了实例演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

其实我们可以使用数组和对象去实现字典结构,但是,我们自己定义一个Dictionary类,让这种字典类型使用起来更加简单,使用()来引用键更加方便;

定义Dictionary类

function Dictionary(){
    this.datastore = new Array();
}

给Dictionary原型添加方法:

Dictionary.prototype = {
//添加方法:
}

一、 添加字典键值的方法

add: function(key, value){
           this.datastore[key] = value;
         }


二、移除某一对键值的方法:

 remove: function(key){
          delete this.datastore[key];
    }


三、打印所有键值对的方法:

 showAll: function(){
        console.log(Object.keys(this.datastore));
        for (var key in this.datastore){
            console.log(key + ':' + this.datastore[key]);
        }
    }


四、获取字典中元素的个数

  count: function(){
        // console.log(this.datastore.length);这个不能用,因为,当键的类型为字符串时,length不能用
        var count = 0;
        for (var i in this.datastore){
            count ++;
        }
        return count;
    }


五、清空字典的内容

clear: function(){
         for (var key in this.datastore){
            delete this.datastore[key];
        }


六、以键值为一定顺序打印

  showSortAll: function(){
        var keys = Object.keys(this.datastore).sort();
        for (var i in keys){
            key = keys[i];
            console.log(key + ":" + this.datastore[key]);
        }
    }



实例:

  var dic = new Dictionary();
      dic.add("c", 3);
      dic.add("a", 2);
      dic.add("b", 9);
      dic.showAll();// c:3 a:2 b:9
      dic.remove('a');
      dic.showAll();// c:3 b:9
      console.log(dic.count());//2
      dic.showSortAll(); b:9 c:3
      dic.clear();
      dic.showAll();// null
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值