使用用户输入搜索数组
问题描述:
我希望能够用用户输入的输入来搜索数组。因此,例如,如果用户在输入字段中输入“18”,根据数字18是否在数组中,“value not found”将出现或出现“value found”。使用用户输入搜索数组
这是我到目前为止。
var search = document.getElementById("search");
var arr = [18,23,20,17,21,18,22,19,18,20];
function beginhere() {
var input = document.getElementById("Input").value;
for (i=0; i<arr.length; i++){
if (arr[i] == Input) {
alert(arr[i]);
} else {
alert("Value not found");
}
}
};
答
你错就错在Input
if (arr[i] == Input) {
敏感i
的情况下应该是
if (arr[i] == input) {
然后你真的不需要else
部分。只需在循环后面写入未找到的警报并在if中写入return语句即可。
function beginhere() {
var input = document.getElementById("Input").value;
for (i=0; i<arr.length; i++){
if (arr[i] == input) {
alert(arr[i]);
return;
}
}
alert("Value not found");
};
而且没有一个循环,你可以尝试
function beginhere() {
var input = document.getElementById("Input").value;
if(arr.indexOf(parseInt(input)) != -1) {
alert(input);
return;
}
alert("Value not found");
};
答
我已经重构你的if
条件,因为现在它提醒与for
循环的每个周期造成的。如果循环在数组中找到给定的数字,记录数字并返回该函数(不需要保持循环活动)。如果不是,则在控制台中找不到该值。
var arr = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
function beginhere() {
var input = document.getElementById("Input").value;
for (i = 0; i < arr.length; i++) {
if (arr[i] == input) {
console.log(arr[i]);
return;
}
}
console.log('value not found');
};
<button onclick="beginhere()">click</button>
<input id='Input'>
另一种可能的解决方案,使用Array#find
。
var arr = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
function beginhere() {
var input = document.getElementById("Input").value,
res = arr.find(v => v == input);
console.log(res ? res : "wasn't found");
};
<button onclick="beginhere()">click</button>
<input id='Input'>
答
你有一些问题:
移动
search
声明和初始化函数里面,因为你需要的实际值,而不是在开始时的值。通过在值的前面添加
plus
将搜索值转换为数字。这使用unary plus+
将值(字符串或数字)转换为数字。用
search
进行测试。退出功能,如果找到
search
。只显示一条消息,如果在循环后没有找到。
var arr = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
function beginhere() {
var search = +document.getElementById("search").value, // need to covert to integer
i; // declaration missing
for (i = 0; i < arr.length; i++) {
if (arr[i] == search) { // use search variable
alert(arr[i]);
return;
}
}
alert("Value not found");
}
<input id="search" type="text" onchange="beginhere()">
JavaScript是大小写敏感的 – charlietfl