我是JS的新手,我试图了解用户如何在输入框中搜索数字,并让javascript向用户提醒数字在数组中的位置,或者它根本不在数组中。我有一个链接到我的小提琴,问题是评论后下半部分的功能。
http://jsfiddle.net/83r24j3j/3/
任何帮助将不胜感激!谢谢。
(请原谅我提前使用document.write
,一些坏习惯很难打破。)
答案 0 :(得分:0)
尝试使用findNumber ...
function findNumber() {
Query = parseInt(document.getElementById(Search).value, 10);
var index = NumberArray.indexOf(Query);
if (index > -1) {
alert(Query + " was found at position " + index);
} else {
alert(Query + " is not found in the array");
}
}
首先,您需要获取函数内的Query值。
其次,使用indexOf
,效率更高。
答案 1 :(得分:0)
var NumberArray = [5, 65, 02,9, 87, 65, 48, 6];
function findnumber() {
var Query = document.getElementById('s').value;
var f = false;
var i;
for (i = 0; i < NumberArray.length; i++) {
if (Query == NumberArray[i]) {
f = true; break; }
}
if(f) alert(Query + " was found at position " + i); else
alert(Query + "is not found in the array");
}
答案 2 :(得分:0)
您的代码中有几个错误:
078
。试试这个:
var NumberArray = [5, 65, 02, 04, 05, 80, 90, 01, 46, 87, 05, 6, 20, 48, 056, 78, 9, 7, 88, 9, 87, 65, 48, 6, 54, 3, 51, 90, 95, 60, 100];
document.write("These are all of the numbers in the array");
document.write("<br>");
document.write(NumberArray);
document.write("<hr>");
var sum = 0;
for (var i = 0; i < NumberArray.length; i++) {
sum += Number(NumberArray[i]);
var average = sum / NumberArray.length;
}
document.write("This is the sum of the array");
document.write("<br>");
document.write(sum);
document.write("<hr>");
document.write("This is the average of the array");
document.write("<br>");
document.write(average);
function findNumber(Query) {
for (i = 0; i < NumberArray.length; i++) {
if (Query == NumberArray[i]) {
alert(Query + " was found at position " + i);
return;
}
}
alert(Query + "is not found in the array");
}
/* Not relevant here
var lookingFor = prompt("who to look for?");
for (i = 0; i < people.length; i++) {
if (lookingFor == people[i]) {
alert(lookingFor + " was found at position " + i);
}
}
*/
&#13;
<title>
Array Search Test
</title>
<body>
<input type="text" id="Search" />
<button onclick="findNumber(document.getElementById('Search').value);">Search Array</button>
<hr />
<script src="external.js"></script>
</body>
&#13;
如果你是javascript的初学者,你应该从最小的代码开始,并在你复杂化时经常测试。不要忘记在控制台中阅读错误消息。
作为旁注,我建议你学习以下内容: