使用数组计算2个输入值之间的值的数量

时间:2017-04-09 11:16:46

标签: javascript arrays

有人可以向我解释为什么这不起作用?代码应该采用用户输入的两个值,并计算输入值之间数组列表中的值的数量。因此,例如,假设用户输入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);

3 个答案:

答案 0 :(得分:1)

  • 将逻辑放入函数中,仅在按钮单击时执行。
  • 使用getElementById抓取输入,并将用户提供的值存储在num1num2变量中。

&#13;
&#13;
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;
&#13;
&#13;

您也可以使用Array#filter执行此操作。此函数将返回一个只包含满足条件的数字的数组。然后,只需检查length属性即可知道剩余的元素数量。

&#13;
&#13;
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;
&#13;
&#13;

答案 1 :(得分:0)

num1num2设置为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;
相关问题