JavaScript数据结构 --- 字典

本文介绍了JavaScript中字典的数据结构实现,包括add、find、remove等操作方法,并通过实例展示了如何使用这些方法来管理键值对数据。此外,还提供了字典中元素个数的统计方法以及清除所有元素的功能。

JavaScript数据结构 --- 字典

字典是一种以 key - value 对形式存储数据的数据结构,就像身份证上的 ID 和名字一样,找到了 ID ,也就确定了名字。
JavaScript 的 Object 类就是以字典形式设计的。

1. 实现 Dictionary 类。
Dictionary 类的基础是 Array 类,而不是 Object 类。

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

定义 add() 方法,该方法接受两个参数:key 和 value。key 是 value 在字典中的索引。

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

定义 find() 方法,该方法以键为参数,返回与其关联的值。

function find(key) {
    return this.datastore[key];
}

使用 JavaScript 中内置函数:delete ,删除 key - value 对,以此定义一个 remove() 方法。

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

再写一个能显示字典中 key - value 对的方法 showAll()。

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



还可以定义一个统计字典中元素个数的方法 count() 。

function count() {
    var n = 0;
    for (var key in Object.keys(this.datastore)) {
        ++n;
    }
    return n;
}

测试代码:

function Dictionary() {
    this.add = add;
    this.datastore = new Array();
    this.find = find;
    this.remove = remove;
    this.showAll = showAll;
    this.count = count;
    this.clear = clear;
}

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 Object.keys(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 Object.keys(this.datastore)) {
        delete this.datastore[key];
    }
}

var test = new Dictionary();
test.add("A", "123");
test.add("B", "456");
test.add("C", "789");
console.log("Number of entries: " + test.count());
console.log("B's Value: ") + test.find("B");
test.showAll();
test.clear();
console.log("Number of entries: " + test.count());

/*
 Number of entries: 3
 B's Value:
 0 -> undefined
 1 -> undefined
 2 -> undefined
 Number of entries: 3
*/

参考资料:
JavaScript高级程序设计
JavaScript MDN
Data Structures and Algorithms with JavaScript

转载于:https://www.cnblogs.com/zhoufulin/p/5007689.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值