HTML文件中有一个多行文本输入框:
<textarea id=”hobbiesInput”></textarea>
允许用户在其中输入自己的兴趣爱好,用户有可能用空格,回车,逗号(全半角都可能),顿号来分隔,写一个函数getUserHobbies(),功能是从输入框中拿到用户输入,经过处理后返回一个没有重复的用户兴趣的字符串数组:
例如:
用户输入:“足球”, “篮球”、“游泳”,“读书”、“看漫画”, “篮球” “游泳”
答案详解:
考察数组去重,标准答案是利用JavaScript对象来做,用两个for循环做去重也行,但是可以继续深入问他,如何降低时间复杂度
第一种对象方法:用while
function getUserHobbies() {
// 获取输入框里内容,考察最基本的document的用法
var userInput = document.getElementById("hobbiesInput").value;
// 把用户输入变成数组,考察简单的正则和数组的常用方法
userInput = userInput.replace(/[,,、\s]+/g, ',');
userInput = userInput.split(',');
// 考察数组去重,标准答案是利用JavaScript对象来做,用两个for循环做去重也行,但是可以继续深入问他,如何降低时间复杂度
var tmpHash = {};
var len = userInput.length;
while (len--) { // 简单的数组循环,用for也正确,用while的可以小加分,可以追问为啥用while。如果他用for的,可以看看是否有把len提前计算出来
if (userInput[len] != "") {
tmpHash[userInput[len]] = true;
}
}
var hobbiesArray = [];
for (var key in tmpHash) {
hobbiesArray.push(key);
}
return hobbiesArray;
}
第一种对象方法:用for
function getUserHobbies() {
// 获取输入框里内容,考察最基本的document的用法
var userInput = document.getElementById("hobbiesInput").value;
// 把用户输入变成数组,考察简单的正则和数组的常用方法
userInput = userInput.replace(/[,,、\s]+/g, ',');
userInput = userInput.split(',');
var tmpHash = {};
var hobbiesArray = [];
for (var i = 0; i < userInput.length; i++) {
var len = userInput[i];
if (tmpHash[len] !== userInput[i]) {
tmpHash[len] = len;
hobbiesArray.push(len)
}
}
alert(hobbiesArray);
}
getUserHobbies();
第二种方法:用两个for循环做
function getUserHobbies() {
// 获取输入框里内容,考察最基本的document的用法
var userInput = document.getElementById("hobbiesInput").value;
// 把用户输入变成数组,考察简单的正则和数组的常用方法
userInput = userInput.replace(/[,,、\s]+/g, ',');
userInput = userInput.split(',');
var hobbiesArray = userInput;
for (var i = 0; i < hobbiesArray.length; i++) {
for (var j = i + 1; j < hobbiesArray.length; j++) {
if (hobbiesArray[i] == hobbiesArray[j]) {
hobbiesArray.splice(i, 1);
i = i - 1;
break;
}
}
}
alert(hobbiesArray);
}
getUserHobbies();
