如何从HTML中的用户输入中查找列表的平均数,最大数和最小数

时间:2019-03-21 23:04:30

标签: javascript html list user-input

我正在尝试编写一个代码,该代码将从用户输入中评估列表中的数字,并计算该列表的总和,平均值,最小值和最大值。我已经从别人的帮助中得到了总和。我似乎找不到如何从列表中获取最大和最小数字。我试图将所有功能(求和,平均值,最大值和最小值)作为按钮使用,就像代码中已经存在的求和按钮一样,当单击该按钮时,会提醒用户该特定功能。

.title { font-weight:bold; margin-top:1em; }
<!DOCTYPE html>

<html>
<head>
  
  <link rel="stylesheet" type="text/css" href="style.css">
  
  </head>
  
  
<body>

  <!--- This only allows the user to input numbers --->
  
  <input type='number' id='input'>
  
  <!--- This is the button that adds the number to the list --->
  
  <input type='button' value='add to list' id='add' disabled="disabled">

  
  <!--- This will list all of the numbers in the list --->
  
  <div class="title">Topics</div>
  <ul id='list'></ul> 
  
   <!--- When clicked, this will alert the user with the sum of their numbers --->
  
  <button id="something">Click Here To See The Sum</button>

  <script>
    
    let list = document.getElementById("list");;
    let btn = document.getElementById("something");
    let input = document.getElementById("input");
    let add = document.getElementById("add");
    
    var sum = 0;
    
    input.addEventListener("input", enableDisable);
    btn.addEventListener("click", sumvar);

    add.addEventListener("click", function() {
      var li = document.createElement("li");
      li.textContent = input.value;
      sum += +input.value; 
      list.appendChild(li);
      input.value = "";  
      add.disabled = "disabled";
    });
   
    // This allows the "add to list" button to be turned on/off depending if the user has typed in a number
      
    function enableDisable(){
     
      if(this.value === ""){
        add.disabled = "disabled";
      } else {
        add.removeAttribute("disabled");
      }
    }
    
    // This function will alert the user of the sum of their numbers
      
    function sumvar() {
      alert("The sum of your numbers is: " + sum);
    }
    
    
  </script>   


</body>
  

  
  
</html>

3 个答案:

答案 0 :(得分:2)

您可以在脚本顶部添加以下两个功能:

    function getNumbersFromList() {
        let numbers = [];
        for (let i = 0; i < list.children.length; i++) {
            numbers.push(parseInt(list.children.item(i).textContent));
        }
        return numbers;
    }

    function getStatsForList() {
        let numbers = getNumbersFromList();
        return {
            sum: numbers.reduce((a, v) => a += v),
            average: numbers.reduce((a, v) => a += v) / numbers.length,
            max: Math.max(...numbers),
            min: Math.min(...numbers)
        }
    }

然后,当您需要样本的更新统计信息时,可以使用getStatsForList()

如果需要,还可以轻松修改该功能以添加更多统计信息...

更新

此版本仅计算一次总和,以后再用于计算平均值。

    function getStatsForList() {
        let numbers = getNumbersFromList();
        let sum = numbers.reduce((a, v) => a += v);
        return {
            sum: sum,
            average: sum / numbers.length,
            max: Math.max(...numbers),
            min: Math.min(...numbers)
        }
    }

答案 1 :(得分:1)

let list = document.getElementById("list");
let input = document.getElementById("input");
let add = document.getElementById("add");
var avg = 0;
var sum = 0;
var min = Infinity;
var max = -Infinity;

// This will add the input number to the list and clear the input

function addClick () {
  var li = document.createElement("li");
  li.textContent = input.value;
  list.appendChild(li);
  update();
  input.value = "";  
  add.disabled = "disabled";
} 

// This allows the "add to list" button to be turned on/off depending if the user has typed in a number

function enableDisable(){
  if(this.value === ""){
    add.disabled = "disabled";
  } else {
    add.removeAttribute("disabled");
  }
}

// This will calculate and update all variable values

function update() {
  sum = 0;
  min = Infinity;
  max = -Infinity;
  var count = 0;
  for (var i of list.children) {
    let val = +i.textContent;
    sum += val;
    if (val > max) max = val;
    if (val < min) min = val;
    count++;
  }
  avg = sum/count;
} 

// This functions will alert the numbers

function sumClick() {
  alert("The sum of your numbers is: " + sum);
}
function avgClick() {
  alert("The average of your numbers is: " + avg);
}
function minClick() {
  alert("The smaller number is: " + min);
}
function maxClick() {
  alert("The greater number is: " + max);
} 

// Here we add all events

input.addEventListener("input", enableDisable);
add.addEventListener("click", addClick);
document.getElementById("avg").addEventListener("click", avgClick);
document.getElementById("sum").addEventListener("click", sumClick); 
document.getElementById("min").addEventListener("click", minClick); 
document.getElementById("max").addEventListener("click", maxClick);
.title { font-weight:bold; margin-top:1em; }
<!--- This only allows the user to input numbers --->
  
  <input type='number' id='input'>
  
  <!--- This is the button that adds the number to the list --->
  
  <input type='button' value='add to list' id='add' disabled="disabled">

  <!--- Here we have a title for the list --->

  <div class="title">Topics</div>

  <!--- This will list all of the numbers --->

  <ul id='list'></ul> 
  
   <!--- When clicked, this buttons alert the user with the numbers --->
  
  <button id="sum">Sum</button>
  <button id="max">Max</button>
  <button id="min">Min</button>
  <button id="avg">Avg</button>

答案 2 :(得分:0)

当添加新项目时,您可以跟踪当前的最小,最大和计数。比较最小和最大并计算平均值。

.title { font-weight:bold; margin-top:1em; }
<!DOCTYPE html>

<html>
<head>
  
  <link rel="stylesheet" type="text/css" href="style.css">
  
  </head>
  
  
<body>

  <!--- This only allows the user to input numbers --->
  
  <input type='number' id='input'>
  
  <!--- This is the button that adds the number to the list --->
  
  <input type='button' value='add to list' id='add' disabled="disabled">

  
  <!--- This will list all of the numbers in the list --->
  
  <div class="title">Topics</div>
  <ul id='list'></ul> 
  
   <!--- When clicked, this will alert the user with the sum of their numbers --->
  
  <button id="something">Click Here To See The Sum</button>

  <script>
    
    
    
    let list = document.getElementById("list");;
    let btn = document.getElementById("something");
    let input = document.getElementById("input");
    let add = document.getElementById("add");
    var firstLoad = 1;
    var sum = 0;
    var avg = 0;
    var min = 0;
    var max = 0;
    var count = 0;
    input.addEventListener("input", enableDisable);
    btn.addEventListener("click", sumvar);

    add.addEventListener("click", function() 
    { 
      var li = document.createElement("li");
      li.textContent = input.value;
      sum += +input.value; 
      count=count+1;
       
      if(firstLoad===1) { 
       min = input.value; //set min and max first time
        max = input.value;
        firstLoad = 0; //clear the firstload marker
      }
      else
      {
      
        if(min > input.value) { //compare input to min
           min = input.value;
        }
        if(max < input.value) { //compare input to max
          max = input.value; //enteredNumber;
        }
      }
      avg = sum/count; //calculate average
      list.appendChild(li);
      input.value = "";  
      add.disabled = "disabled";
    });
    
    function enableDisable() { 
      if(this.value === ""){
        add.disabled = "disabled";
      } else {
        add.removeAttribute("disabled");
      }
    }
    
    // This function will alert the user of the sum of their numbers
      
    function sumvar() {
      alert("sum:" + sum + ",avg:" + avg + ",min:" + min + ",max:" + max);
    }
    
    
  </script>   


</body>
  

  
  
</html>