如何创建一个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;
})
这已经尝试了
答案 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>