繁体   English   中英

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

[英]How do I create a Javascript that finds average at every clicks on a button

如何创建一个 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;
})

这显示了我的尝试。

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

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

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM