Count number of values in array between two input values

前端 未结 4 1789
鱼传尺愫
鱼传尺愫 2021-01-28 17:05

As the title suggests, I want to create a function the counts the number of values in my array between two values that have been entered by the user. So for example, if the arra

4条回答
  •  难免孤独
    2021-01-28 17:14

    All you need is a simple for loop.

    var total = 0;
    var num1 = 5;
    var num2 = 7;
    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);
    

    This will loop through the array, detect nums within the range, tally up a value, and output it in a alert.

提交回复
热议问题