1. 写一个程序,该程序从一个文本文件中读入名字和电话号码,然后将其存入一个字典。 该程序需包含如下功能:显示单个电话号码、显示所有电话号码、增加新电话号码、删 除电话号码、清空所有电话号码。
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];
}
function showAll() {
var keys = Object.keys(this.dataStore);
keys.sort();
keys.forEach(function(key) {
console.log(key + " -> " + this.dataStore[key]);
}, this);
/*
for(var key in this.datastore) {
if (this.dataStore.hasOwnProperty(key)) {
console.log(key + " -> " + this.datastore[key]);
}
}*/
}
function count() {
var n = 0;
for (var key in this.dataStore) {
if (this.dataStore.hasOwnProperty(key)) {
n++;
}
}
return n;
}
function clear() {
for (var key in this.dataStore) {
if (this.dataStore.hasOwnProperty(key)) {
delete this.dataStore[key];
}
}
}
function main() {
var phoneBook = new Dictionary();
while (true) {
console.log("\n电话簿管理程序");
console.log("1. 增加新电话号码");
console.log("2. 显示单个电话号码");
console.log("3. 显示所有电话号码");
console.log("4. 删除电话号码");
console.log("5. 清空所有电话号码");
console.log("6. 退出程序");
var choice = prompt("请选择操作 (1-6): ");
switch (choice) {
case '1':
var nameToAdd = prompt("请输入名字: ");
var numberToAdd = prompt("请输入电话号码: ");
phoneBook.add(nameToAdd, numberToAdd);
console.log("电话号码已添加");
break;
case '2':
var nameToFind = prompt("请输入名字: ");
var numberFound = phoneBook.find(nameToFind);
if (numberFound) {
console.log(nameToFind +" 的电话号码是 " + numberFound);
} else {
console.log("未找到该名字");
}
break;
case '3':
console.log("所有电话号码:");
phoneBook.showAll();
break;
case '4':
var nameToRemove = prompt("请输入名字: ");
phoneBook.remove(nameToRemove);
console.log("电话号码已删除");
break;
case '5':
phoneBook.clear();
console.log("所有电话号码已清空");
break;
case '6':
console.log("退出程序");
return;
default:
console.log("无效的选择,请重新选择");
}
}
}
main();
2. 使用 Dictionary 类写一个程序,该程序用来存储一段文本中各个单词出现的次数。该程 序显示每个单词出现的次数,但每个单词只显示一次。比如下面一段话“the brown fox jumped over the blue fox”,程序的输出应为: the: 2 brown: 1 fox: 2 jumped: 1 over: 1 blue: 1
function main() {
var text = prompt("请输入一段文本:");
var wordCounts = new Dictionary();
var words = text.toLowerCase().match(/\b\w+\b/g);
words.forEach(word => {
var currentCount = wordCounts.find(word) || 0;
wordCounts.add(word, currentCount + 1);
});
console.log("每个单词出现的次数:");
wordCounts.showAll();
}
main();
3. 修改练习 2,使单词按字母顺序显示。
function showAll() {
var keys = Object.keys(this.dataStore);
keys.sort();
keys.forEach(function(key) {
console.log(key + " -> " + this.dataStore[key]);
}, this);
/*
for(var key in this.datastore) {
if (this.dataStore.hasOwnProperty(key)) {
console.log(key + " -> " + this.datastore[key]);
}
}*/
}