如何创建一个javascript,可以在按钮的每次点击时找到平均值

时间:2017-04-02 02:31:18

标签: javascript javascript-events

如何创建一个Javascript程序,找到每次点击查找按钮时在文本框中输入的数字的平均值

var all=[];
$(document).on('click', 'check', function()
{
    var second, minute, hours, aht;
    second = document.getElementById('sec').value;
    minute = document.getElementById('min').value;
    hours = document.getElementById('hour').value;

    nocAll.push = (eval(second + (minute * 60) + (hours * 60 *60)));

    for(var i =0; i< nocAll.length; i++);
    sum += parseInt(nocAll.elmt[i], 10);
    aht = sum/nocAll.length;

    document.getElementById("AHT").innerHTML = aht;
})

这已经尝试了

1 个答案:

答案 0 :(得分:0)

您编辑了问题,因此这是一种方法。

您的代码中存在一些问题。

nocAll 未定义(我认为您打算使用all

Array.prototype.push是一个函数all.push(value)

var all = [];
// cache the elements you will be working with
var $second = $('#sec')
var $minute = $('#min')
var $hour = $('#hour')
var $aht = $("#AHT")
// add two numbers together
var add = function(a, b) {
  return a + b
}

$(document).on('click', '.check', function() {
  // get the current values of the inputs and convert to seconds
  var hours   = Number($hour.val()) * 60 * 60
  var minutes = Number($minute.val()) * 60
  var seconds = Number($second.val())
  // add total time in seconds to the all array
  all.push(hours + minutes + seconds)
  // just for dubugging
  console.log(all)
  // calculate the average by folding the array and adding the values
  // then divide by the length
  $aht.html('average seconds:' + all.reduce(add, 0) / all.length)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="hour" placeholder="hours" />
<input type="text" id="min" placeholder="minutes" />
<input type="text" id="sec" placeholder="seconds" />
<button class="check">check</button>
<div id="AHT"></div>