【问题标题】:How to find average, maximum, and minimum numbers of a list from user input in HTML如何从 HTML 中的用户输入中查找列表的平均值、最大值和最小值
【发布时间】:2019-08-12 21:41:10
【问题描述】:

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

.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>

【问题讨论】:

    标签: javascript html list user-input


    【解决方案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>

    【讨论】:

    • 除了最小值之外,这非常有效。当我输入数字 1、2、3、4、5 并单击“min”按钮时,它表示该值为无穷大。这只发生在最小值位于列表的第一个位置时。我该如何解决这个问题?
    • 这是一个错字,我也发现它并在发布后立即修复。
    • 我复制了新的 sn-p,但我仍然不知道如何解决这个问题。最小值确实有效,只是在最小值是第一个值时无效。如果我输入 0,1,2,3 并单击“min”,我会收到 Infinity 提示。当我输入 1,2,3,0 时,最小值为 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)
            }
        }
    

    【讨论】:

    • 喜欢在 ES6 中使用 Math.max/min,非常易读(旧浏览器需要 babel)。不确定这两个减少是否会随着列表的增长而产生影响。
    • @rafaelcastrocouto 我同意计算总和两次(一次用于求和,一次用于平均值)在这里是不必要的。应该对总和执行一次,然后重新用于平均值。
    【解决方案3】:

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

    .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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-16
      • 1970-01-01
      • 2014-04-23
      • 2018-08-17
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多