数据结构篇——字典 发表于 2018-11-10 | 分类于 数据结构 字典是一种以键值对形式存储数据的数据结构,JavaScript的Object类就是以字典的形式设计的。 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162function Dictionary(){ this.dataStore = new Array(); this.add = add; 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() { if (Object.keys(this.dataStore).length == 0){ console.log('null') } for (let key of Object.keys(this.dataStore).sort()) { // 对键值进行排序 console.log(key + '->' + this.dataStore[key]); }}function count(){ return Object.keys(this.dataStore).length; // 方法二 // let n = 0; // for (let key in Object.keys(this.dataStore)){ // n++; // } // return n;}function clear(){ for(let key of Object.keys(this.dataStore)){ delete this.dataStore[key]; }}// 测试代码let book = new Dictionary();book.add('c', '1');book.add('b', '2');book.add('a', '3');console.log('a的值为:'+book.find('a'));book.remove('b')console.log(book.count());book.showAll();book.clear();book.showAll();console.log(book.count());