一、字典类字典类(dictionary)基于object。在《数据结构与算法javascript描述》书中“字典”采用了数组存储数据,不仅让阅读者很难理解,而且也没有实现便捷性,反而其中的代码逻辑是错误的,不能按照设计的方式正确输出结果!!!
/** * 构造函数 * 基于对象存储数据 * @constructor */function dictionary(){ this.datastore = new object(); } dictionary.prototype = { /* 修正constructor */ constructor: dictionary, /* 统计个数 */ size: function(){ return object.keys(this.datastore).length; }, /* 添加元素,给数组添加属性 */ add: function(key, value){ this.datastore[key] = value; }, /* 查找指定key的元素 */ find: function(key){ return this.datastore[key]; }, /* 移除指定key的元素 */ remove: function(key){ delete this.datastore[key]; }, /* 显示所有的键值对 */ showall: function(){ for(var key in this.datastore){ console.log(key + ": " + this.find(key)); } } };
测试:
var dic = new dictionary(); dic.add("name", "ligang"); dic.add("age", 26); dic.find("name"); // "ligang"dic.size(); // 2dic.showall(); // "name: ligang" "age: 26"dic.remove("age"); dic.size(); // 1dic.showall(); // "name: ligang"
补充:object.keys(obj)返回一个数组,包含所有(自身)可枚举属性。请查看-javascript对象、函数(你不知道的javascript)
二、为字典类添加排序功能为字典排序,可以转化为某个对象属性排序。所以我们可以借助object.keys()
/* 排序 */dictionary.prototype.sort = function(){ // 借助数组的默认排序 var keys = object.keys(this.datastore).sort(); // 新定义字典类 var tempdic = new dictionary(); for(var i = 0, len = keys.length; i < len; i++){ var key = keys[i]; tempdic.add(key, this.find(key)); } return tempdic; };
测试:
var dictionary = new dictionary(); dictionary.add("b", 2); dictionary.add("a", 1); dictionary.add("c", 3); dictionary.showall(); // "b: 2" "a: 1" "c: 3"dictionary.sort().showall(); // "a: 2" "b: 1" "c: 3"
总结:上述字典类不允许出现重复的key。对于相同的key,后面的会覆盖前面的。当然,可以通过修改代码实现其他方式。
相关推荐:
字典类型
javascript字典操作
js数组,字典
以上就是详解javascript数据结构之字典类的详细内容。
