JavaScript数据结构 --- 字典
2015-11-30 16:59
501 查看
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
相关文章推荐
- 第13周SHH数据结构-【项目5-拓扑排序算法的验证 】
- 第十二周--数据结构--图的遍历
- 数据结构——双向链表(Java实现)
- 数据结构实践——Prim算法的验证
- OpenCv学习笔记(三)——openCv数据结构之间的转换
- 项目3 - 是否二叉排序树?
- 项目2 二叉树排序树中查找的路径
- 【第13周-图项目5——拓扑排序算法验证】
- 数据结构实践——迷宫问题之图深度优先遍历解法
- 项目1.4 验证平衡二叉树相关算法
- 数据结构实践——图遍历算法实现
- 项目1.3 验证二叉排序树
- 第14周 项目1-数据结构例程——线性表的折半查找
- 项目1.2 验证分块查找算法
- 项目1.1.2 递归的折半查找算法
- 第十四周 项目1.1.1 折半查找
- 数据结构--Chapter2(线性表)
- redis数据结构
- 数据结构例程——选择排序之直接选择排序
- 数据结构例程—— 交换排序之快速排序