数据结构——字典(JavaScript)

创建字典

function Dictionary(){//首先申明一个类
    var items = {};
    this.set = function(Key,value){//向字典中添加新元素
        items[Key] = value;
    }
    this.remove = function(Key){//通过使用键值对来从字典中移除键值对应的数据值
        if(Key in items){
            delete items[Key];
            return true;
        }else{
            return false;
        }
    }
    this.has = function(Key){//如果某个键值存在于这个字典中,就返回true,否则返回false
        return Key in items;
    }
    this.get = function(Key){//通过键值查找指定的数值并返回
        return this.has(Key) ? items[Key] : undefined;
    }
    this.clear = function(){//删除字典中所有的元素
        items = {};
        return true;
    }
    this.size = function(){//返回字典所包含元素的数量
        return this.Keys().length;
    }
    this.Keys = function(){
        var keys = [];
        for(var k in items){
            if(this.has(k)){
                keys.push(k);
            }
        }
        return keys;
    }
    this.values = function(){//将字典所包含的所有数值以数组形式返回
        var values = [];
        for(var k in items){
            if(this.has(k)){
                values.push(items[k]);
            }
        }
        return values;
    }
    this.getItems = function(){
        return items;
    }
}

使用Dictionary类

var dictionary = new Dictionary();
dictionary.set('Tom','123@qq.com');
dictionary.set('Bob','456@163.com');
dictionary.set('John','789@126.com');
console.log(dictionary.has('Tom'));
console.log(dictionary.size());
console.log(dictionary.Keys());
console.log(dictionary.values());
console.log(dictionary.get('Bob'));
console.log(dictionary.remove('John'));
console.log(dictionary.size());
console.log(dictionary.Keys());
console.log(dictionary.values());
console.log(dictionary.getItems());

控制台输出

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值