//字典是键值对存储数据的数据结构
//这里我们定义一个Dictionary类
function Dictionary() { this.dataStore = new Array(); this.add = add; this.find = find; //this.remove=remove; this.showAll = showAll; }
//先来定义add方法,接受键值两个参数、
function add(key, value) { this.dataStore[key] = value; }
//接下来定义find方法,接受key参数,返回和其相关的值
function find(key) { return this.dataStore[key] }
//从字典中删除需要js内置函数delete,因为函数是object这个类的一部分
function remove(key) { delete this.dataStore[key] }
//最后,我们希望可以显示字典中所有的键值对;
function showAll() { for (var key in Object.keys(this.dataStore)) { console.log(key + " --> " + this.dataStore[key]) } }
//下面我们来测试:
var book = new Dictionary(); book.add("Mike", "123"); book.add("David", "345"); book.add("Cynthia", "456"); book.showAll(); console.log("david's extension:" + book.find("David")); //pbook.remove("David"); book.showAll();