js 字典与Map对象

 字典 是一种以键-值对形式存储数据的数据结构,像电话簿里面的电话和号码一样,本文字典的的基础类为Array.

字典实现:

function Dictionary() {
    this.datastore = [];
    this.add = add;
    this.find = find;
    this.remove = remove;
    this.showAll = showAll;
    this.count = count;
    this.clear = clear;
    this.kSort = kSort;
    this.vSort = vSort
}
//添加
function add(key,value) {
    this.datastore[key] = value;
}
//查找
function find(key) {
    return this.datastore[key];
}
//删除
function remove(key) {
    delete this.datastore[key];
}
//显示所有键值对
function showAll() {
    for (var key in this.datastore) {
        console.log(key + ':' + this.datastore[key]);
    }
}
//计数
function count() {
    var n = 0;
    for (var key in Object.keys(this.datastore)) {
        n++;
    }
    return n;
}
//清空字典
function clear() {
    for (var key in this.datastore) {
        delete this.datastore[key];
    }
}
// 按键(key)排序,升序
function kSort(){
    var dic = this.datastore;
    var res = Object.keys(dic).sort();
    for(var key in res ){
        console.log(res[key] + " : " + dic[res[key]]);
    }
}
// 按键(key)排序,降序
function vSort(){
    var dic = this.datastore;
    var res = Object.keys(dic).sort(function(a,b){
        return dic[a]-dic[b];
    });
    for(var key in res ){
        console.log(res[key] + " : " + dic[res[key]]);
    }
}

var pbook = new Dictionary();
//添加键值对
pbook.add("Mike","123");
pbook.add("David", "345");
pbook.add("Cynthia", "456");
pbook.add("Cyntddhia", "456");
//显示所有数据
pbook.showAll();
//显示数量
pbook.count();
//排序
pbook.vSort()

Map 结构的实例有以下属性和操作方法

(1)size 属性

size属性返回 Map 结构的成员总数。

const map = new Map();
map.set('foo', true);
map.set('bar', false);

map.size // 2
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值