首页 > 代码库 > js字典的两道练习题

js字典的两道练习题

1.从一个文本文件中读入名字和电话号码,然后将其存入一个字典。程序的功能包括:显示单个电话号码、显示所有的电话号码、增加新的电话号码。

2.程序存储一段文本中各个单词出现的次数。功能:显示每个单词出现的次数,但每个单词只显示一次。

编程:

function dictionary(){
this.dataStore = new Array();
this.displaySingle = displaySingle;
this.displayAll = displayAll;
this.insertTle = insertTle;
this.removeTle = removeTle;
this.clear = clear;
this.containsKey = containsKey;

}

function displaySingle(key){
console.log(this.dataStore[key]);
}
function displayAll(){
for(var key in this.dataStore){
console.log(key+"->"+this.dataStore[key]);
}
}
function containsKey(checkKey){
for(var key in this.dataStore){
if(key == checkKey){
return true;
}
}
}
function insertTle(key,value){
if(this.containsKey(key)){//有字典值
this.dataStore[key] = parseInt(value)+1;
}else{//无字典值
this.dataStore[key] = value;
}

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

测试练习题1:

var peopleTle = new dictionary();
peopleTle.insertTle("R",123456);
peopleTle.insertTle("A",223333);
peopleTle.insertTle("B",854845);
peopleTle.insertTle("C",777878);
peopleTle.insertTle("D",6966587);
peopleTle.displaySingle("B");
peopleTle.displayAll();
peopleTle.removeTle("C");
peopleTle.displayAll();
peopleTle.clear();
peopleTle.displayAll();

测试练习题2:

var str1 = ["this","is","a","fly","the","name","is","a"];

var str2 = "this mt ctt dt dt rt ot tp rt this this mt";


String.prototype.trim = function() {//去空格处理
var str = this,
str = str.replace(/^\s\s*/, ","),
ws = /\s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
}

var t = str2.trim();
console.log(t);
console.log(str2);
console.log(typeof (t));
var arr2 = t.replace(/\s/g,",").split(",");
var arr3 = [];
for(var i=0;i<arr2.length;i++){
arr3.push(arr2[i]);
}


function checkNum(str1){
var word = new dictionary();
for(var i = 0;i<str1.length;i++){
if(str1[i]==""||str1[i]==undefined||str1[i]==null){
return false;
}else{
word.insertTle(str1[i],1);
}
}
word.displayAll()
}
checkNum(str1);
console.log("&&&&&&&&&&&&&&&&&&&&");
checkNum(arr3);

 

js字典的两道练习题