字典
JavaScript 的 Object 类就是以字典的形式设计的
Dictionay 类的基础是 Array 类, 而不是 Object 类
Array数组也可以定义索引为字符串如下:
var array = [1,2,3]; array["abc"] = "abc"; console.log(array["abc"]);// abc
删除数组方式:
delete array[1]; // [1, undefined, 3] 和 "abc"的索引
索引还在,值为undefined;
那么删除"abc"呢?
delete array["abc"];
结果是直接删除了索引和值一起删除了
如果向数组中添加一个值?
array[3] =4; array[4] = 5; array.push(6); console.log(array["abc"]);//[1, 2, 3, 4, 5, 6]
通过array["abc"] 向数组中插入数据,不会影响数组中的索引排列顺序.
length属性
console.log(array.length); // 6
为什么是数组个数是6个而不是7个吗?
原因:这是因为当键的类型为字符串时, length 属性就不管用了
字典定义方法:
add() // 添加 dataStore = new Array(); // 字典内部定义了一个数组 find(); // 查找 remoe(); // 删除 showAll();// 显示 count(); // 字典个数 clear(); // 清空字典
完整字典代码:
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 each(var key in Object.keys(this.datastore)) {
print(key + " -> " + this.datastore[key]);
}
}
function count() {
var n = 0;
for each(var key in Object.keys(this.datastore)) {++n;
}
return n;
}
function clear() {
for each(var key in Object.keys(this.datastore)) {
delete this.datastore[key];
}
}原文地址:http://51web.blog.51cto.com/4386311/1638295