字典的含义
字典是一种以键 - 值对形式存储数据的数据结构,就像电话号码簿里的名字和电话号码一 样。要找一个电话时,先找名字,名字找到了,紧挨着它的电话号码也就找到了。字典是一种跟set集合很相似的数据结构,都可以用来存储无序不重复的数据。不同的地方是集合以[值,值]的形式存储,而字典则是以[键,值]或者叫作{key: value}的形式。
JS代码实现
function 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];
}
//当键为字符串时,length属性无效
function count()
{
let n=0;
for(let key of Object.keys(this.dataStore)){
n++;
}
return n;
}
function showAll()
{ //for in是ES5标准,遍历key. for of是ES6标准,遍历value.
for(let key of Object.keys(this.dataStore).sort()){
console.log(key+"->"+this.dataStore[key]);
}
}
function clear()
{
for(let key of Object.keys(this.dataStore)){
delete this.dataStore[key];
}
}
let pbook=new Dictionary();
pbook.add("Mike","123");
pbook.add("David", "345");
pbook.add("Cynthia", "456");
console.log("Number of entries:"+pbook.count());
console.log("David's extension: " + pbook.find("David"));
pbook.remove("David");
pbook.showAll()
pbook.clear();
console.log("Number of entries:"+pbook.count());
module.exports=Dictionary;
字典习题
1.写一个程序,该程序从一个文本文件中读入名字和电话号码,然后将其存入一个字典。该程序需包含如下功能:显示单个电话号码,显示所有电话号码,增加新电话号码、删除电话号码、清空所有电话号码
const fs=require('fs');
const Dictionary=require("./lesson6-1.js");
//从tel.txt文件中获取联系人信息
function getTelphone(dictionary)
{
let tels=fs.readFileSync('tel.txt','utf-8').split("\n");
for(let i=0;i<tels.length;i++){
tels[i]=tels[i].trim();//清除空格
let address=tels[i].split(" ");
dictionary.add(address[0],address[1]);
}
}
//显示单个电话号码
Dictionary.prototype.showSingle=function(name){
console.log(name+"->"+this.find(name));
}
let d=new Dictionary();
getTelphone(d);
//展示所有电话号码
console.log(d.showAll());
//增加电话号码
d.add('Jack','15071416731')
//展示单个电话号码
d.showSingle('Jack');
//删除电话号码
console.log("删除Tom");
d.remove('Tom');
d.showAll();
//删除所有
console.log("删除所有");
d.clear();
d.showAll();
2.使用 Dictionary 类写一个程序,该程序用来存储一段文本中各个单词出现的次数。该程序显示每个单词出现的次数,但每个单词只显示一次。比如下面一段话“the brown fox jumped over the blue fox”,程序的输出应为:
the: 2
brown: 1
fox: 2
jumped: 1
over: 1
blue: 1
//统计
Dictionary.prototype.addCount=function(key){
this.dataStore[key]=this.find(key)?this.dataStore[key]+1:1;
}
//解析句子
Dictionary.prototype.analysis=function(sentence){
let words=sentence.split(" ");
for(let key of words){
this.addCount(key);
}
}
let sentence="the brown fox jumped over the blue fox";
let d=new Dictionary();
d.analysis(sentence);
d.showAll();