数据结构与算法-字典

  • 字典以一种键-值对形式存储
  • JavaScript的Object类就是以字典的形式设计的。我们要实现一个Dictionary类,这样会比Object方便,比如显示字典中的所有元素,对属性进行排序等
function Dictionary(){  
  this.dataStore = new Array();
  this.add = add;
  this.find = find;
  this.count = count;
  this.clear = clear;
  this.remove = remove;
  this.showAll = showAll;
}
function add(key, value){  
  this.dataStore[key] = value;
}
function find(key){  
  return this.dataStore[key];
}
function remove(key){  
  delete this.dataStore[key];
}
function showAll(){  
  var datakeys = Object.keys(this.dataStore).sort();
  for(var keys in datakeys){
    console.log(datakeys[keys]+"-->"+this.dataStore[datakeys[keys]]);
  }
}
function count(){  
  return Object.keys(this.dataStore).length;
}
function clear(){  
  var datakeys = Object.keys(this.dataStore);
  for(var keys in datakeys){
    delete this.dataStore[datakeys[keys]];
  }
}
var pbook = new Dictionary();  
pbook.add('e','1');  
pbook.add('b','2');  
pbook.add('f','3');  
pbook.add('d','4');  
//console.log(pbook.find('c'));
pbook.showAll(); 

作者:@lsxlsxxslxsl