字典
字典是一种以键-值对形式存储数据的数据结构
最基本功能规划
add 添加数据到字典
remove 从字典中移除数据
get 从字典中取出数据
count 统计字典数据量
find 查找数据在字典中位置
show 显示字典数据
/**
* 字典
* @constructor
*/
function Dictionary(){
var me = this;
me.dataStore = [];
me.add = add;
me.find = find;
me.remove = remove;
me.clear = clear;
me.count = count;
me.showAll = showAll;
function add(key,value){
me.dataStore[key] = value;
}
function find(key){
return me.dataStore[key] ;
}
function remove(key){
delete me.dataStore[key]
}
function clear(){
for(var i in Object.keys(me.dataStore)){
delete me.dataStore[i];
}
}
function showAll (){
var list = Object.keys(me.dataStore).sort(),s=' ';
list.forEach(function(item){
s+= "key: "+item;
s+= ",value: "+me.dataStore[item] +"
"
})
console.log(s)
}
function count(){
var list = Object.keys(me.dataStore),n=0;
list.forEach(function(){
++n;
})
return n;
}
}
test
var pbook = new Dictionary();
pbook.add("Raymond","123");
pbook.add("David", "345");
pbook.add("Cynthia", "456");
pbook.add("Mike", "723");
pbook.add("Jennifer", "987");
pbook.add("Danny", "012");
pbook.add("Jonathan", "666");
pbook.add("Accccc", "666");
pbook.showAll();
console.log(pbook.find('Accccc'))
console.log(pbook.count())
//提取字符出现次数
var s = "the brown fox jumped over the blue fox";
var stotal = new Dictionary();
var sarr = s.split(' ');
for(var i = 0,n= sarr.length;i<n;i++){
if(stotal.find(sarr[i])){
var v = stotal.find(sarr[i]);
stotal.remove(sarr[i])
stotal.add(sarr[i],v+1)
}else{
stotal.add(sarr[i],1)
}
}
stotal.showAll();