JavaScript数据结构 --- 字典

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() 。 ```js 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

posted @ 2015-11-30 16:59  周福林  阅读(355)  评论(0编辑  收藏  举报