[英]How do I create a Javascript that finds average at every clicks on a button
How do I create a Javascript program that find the average of numbers entered in text box every time the find button is click?如何创建一个 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;
})
This shows what I have tried.这显示了我的尝试。
You edited your question so here is a way to do it.您编辑了您的问题,因此这是一种方法。
You have a few problems in your code.您的代码中存在一些问题。
nocAll
is undefined (I think you meant to use all
nocAll
未定义(我认为您打算使用all
Array.prototype.push
is a function, all.push(value)
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.