有人可以向我解释为什么这不起作用?代码应该采用用户输入的两个值,并计算输入值之间数组列表中的值的数量。因此,例如,假设用户输入5作为他们的第一个值,7作为他们的第二个值,因为他们是5到7之间的数组中的3个值,将弹出一个提示“值的总数= 3”。但是在我运行代码的那一刻,它只是说值的总数是0?这是为什么?
这是我的HTML:
<!DOCTYPE html>
<body>
<input type="text" id="num1"></input>
<input type="text" id="num2"></input>
<button onclick="start()" type = "button">search</button>
<script src="array.js"></script>
</body>
这是我的JavaScript:
var total = 0;
var num1 = "";
var num2 = "";
var array = [1,4,6,7,8,6];
for(var a = 0; a < array.length; a++) {
if(array[a] >= num1 && array[a] <= num2) {
total++;
}
}
alert("Total numbers of values = " + total);
答案 0 :(得分:1)
getElementById
抓取输入,并将用户提供的值存储在num1
和num2
变量中。
function start() {
var total = 0;
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var array = [1, 4, 6, 7, 8, 6];
for (var a = 0; a < array.length; a++) {
if (array[a] >= num1 && array[a] <= num2) {
total++;
}
}
alert("Total numbers of values = " + total);
}
&#13;
<input type="text" id="num1">
<input type="text" id="num2">
<button onclick="start()" type="button">search</button>
&#13;
您也可以使用Array#filter
执行此操作。此函数将返回一个只包含满足条件的数字的数组。然后,只需检查length
属性即可知道剩余的元素数量。
function start() {
var num1 = document.getElementById('num1').value,
num2 = document.getElementById('num2').value,
array = [1, 4, 6, 7, 8, 6],
res = array.filter(v => v >= num1 && v <= num2).length;
alert("Total numbers of values = " + res);
}
&#13;
<input type="text" id="num1">
<input type="text" id="num2">
<button onclick="start()" type="button">search</button>
&#13;
答案 1 :(得分:0)
将num1
和num2
设置为input
值。
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
答案 2 :(得分:0)
您的代码没问题,您可以在这里更改
var num1 = "";
var num2 = "";
您的代码就像
一样var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;