如何计算提交到输入字段的数字平均值?

时间:2017-11-09 23:19:45

标签: javascript arrays

这是我的代码:

平均成绩

功能dosomething {   var i = Number;  var numbers = new Array {a,b,c};         数字[0] = a;         数字[1] = b;         数字[2] = c;  var total = 0;     for(i = 0; i
</head>

<body>
 <p id= "functionOutput"></p>

<input type="text" id="input" />

<input type= "button" id="enter" onclick="dosomething(input.value)" 
value="Calculate" />

</body>
</html>

1 个答案:

答案 0 :(得分:0)

要做到这一点,你需要做两件事:

  1. 按下按钮时收集输入的数值并存储在数组中
  2. 计算数组内容的平均值
  3. 1。收集/存储输入数值

    var calculate_btn = document.getElementById('enter'),
        input_field = document.getElementById('input'),
        all_values = [];
    
    // store input value to array when button is clicked
    calculate_btn.addEventListener('click', function(){
      var input_value = parseFloat( input_field.value );
    
      // ensure it is a number
      if( isNaN( input_value ) ) return;
    
      all_values.push( input_value );
    });
    

    2。计算数组内容的平均值

    function get_input_value_average(){
    
      // calculate new average
      var total = 0,
          average;
    
      all_values.forEach( function( entry ){
        total += entry;
      });
    
      average = total / all_values.length;
      return average;
    }
    

    全力以赴

    将此脚本标记放在</body>标记之前:

    <script>
    
      var calculate_btn = document.getElementById('enter'),
          input_field = document.getElementById('input'),
          all_values = [];
    
      // store input value to array when button is clicked
      calculate_btn.addEventListener('click', function(){
        var input_value = parseFloat( input_field.value );
    
        // ensure it is a number
        if( isNaN( input_value ) ) return;
    
        all_values.push( input_value );
    
        var input_average = get_input_value_average();
    
        alert( 'average: ' + input_average + ' | entries: ' + all_values.join( ', ' ) );
      });
    
      function get_input_value_average(){
    
        // calculate new average
        var total = 0,
            average;
    
        all_values.forEach( function( entry ){
          total += entry;
        });
    
        average = total / all_values.length;
        return average;
      }
    </script>
    

    应该这样做。