字典是一种以键 - 值对形式存储数据的数据结构
通过数组实现字典
function Dictionary() { this.add = add; this.datastore = new Array(); this.find = find; this.remove = remove; this.showAll = showAll; this.count = count; this.clear = clear; }
add() 方法接受两个参数:键和值
function add(key, value) { this.datastore[key] = value; }
find() 方法以键作为参数,返回和其关联的值
function find(key) { return this.datastore[key]; }
remove() 方法从字典中删除键 - 值对
function remove(key) { delete this.datastore[key]; }
showAll() 方法显示字典中所有的键 - 值对
function showAll() { for (var key in this.datastore) { console.log(key + " -> " + this.datastore[key]); } }
count() 方法显示字典中的元素个数
function count() { var n = 0; for (var key in this.datastore) { ++n; } return n; }
clear() 方法清空键值对
function clear() { for(var key in this.datastore) { delete this.datastore[key]; } }