# JS中的算法与数据结构——字典(Dictionary)

## 字典的实现

``````//字典类

function Dictionary () {
this.dataStore = [];
this.find = find;       // 查找元素
this.remove = remove;   // 删除元素
this.count = count;     // 字典中元素个数
this.showAll = showAll; // 显示字典元素
this.clear = clear;     // 清空字典
}
``````

``````//向字典添加元素

function add( key , value ){
this.dataStore[key] = value;
}
``````

find：查找字典中的元素

``````//查找字典中的元素

function find( key ){
return this.dataStore[key];
}
``````

remove：删除字典中的一个元素

``````//删除一个元素

function remove( key ){
if( this.dataStore[key] ) delete this.dataStore[key];
}
``````

showAll：显示字典中所以键值对

``````//显示字典元素

function showAll () {
for( var key in this.dataStore ){
console.log( key + '->' + this.dataStore[key] );
}
}
``````

``````//实例化字典类

var directory = new Dictionary();

//添加元素

//显示字典

directory.showAll();         // Jack->138****5505
// Alice->156****6606
// Tom->180****8808

directory.remove( 'Tom' );
directory.showAll();         // Jack->138****5505
// Alice->156****6606
``````

count：查看字典中元素的个数

``````//查看字典中元素的个数

function count(){
var n = 0 ;
for ( var key in this.dataStore ){
++n;
}
return n;
}
``````

``````var nums = [ 0 , 1 , 2 ] ;

console.log(nums.length)        // 3

var directory = [];
directory['Jack'] = '138****5505';
directory['Alice'] = '156****6606';
directory['Tom'] = '180****8808';

console.log(directory.length)   // 0
``````

clear：清空字典

``````//清空字典

function clear(){
for( var key in this.dataStore ){
delete this.dataStore[key];
}
}
``````

``````console.log(directory.count());     // 2
directory.clear();
console.log(directory.count());     // 0
``````

``````//改造后的showAll

function showAll(){
var sortKeys = Object.keys(this.dataStore).sort();
for( var key in sortKeys ){
console.log( sortKeys[key] + '->' + this.dataStore[sortKeys[key]] );
}
}
``````

``````// 重新打印上述字典

directory.showAll();        //  Alice->156****6606
//  Jack->138****5505
//  Tom->180****8808
``````

``````//sortKeys

["Alice", "Jack", "Tom"]
``````