如何解决无法使用jQuery获得正确的平均持续时间
我已经创建并记录了日志工具,该工具可以跟踪条目创建日期时间,条目开始日期时间,条目结束日期时间。
如何获取平均值,请参见下面的示例
个人的2个条目,如下所示 00:04:21和00:21:04
我从jquery代码中获得了这些条目
<script>
$(document).ready(function () {
var pad = function (num) { return ("0" + num).slice(-2); }
var totalSeconds = 0;
var reslength = $(".totalColumn").length;
$(".totalColumn").each(function () {
var currentDuration = $(this).text();
currentDuration = currentDuration.split(":");
var hrs = parseInt(currentDuration[0]);
var min = parseInt(currentDuration[1]);
var sec = parseInt(currentDuration[2]);
var currDurationSec = sec + (60 * min) + (60 * 60 * hrs);
totalSeconds += currDurationSec;
});
var hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
var minutes = Math.floor(totalSeconds / 60);
var seconds = totalSeconds % 60;
$(".showResTime").text(pad(hours) + ":" + pad(minutes) + ":" + pad(seconds) / reslength);
});
</script>
使用上述jQuery代码的结果显示为00:25:12.5这是不正确的
如果我们在Excel上计算此结果如下 00:04:21 + 00:21:04 / 2 = 00:23:14这似乎是正确的。
如何使用jquery获得正确的平均值
解决方法
我已经更新了您的代码以生成您想要的东西。发生的事情是,在获得总计秒数之后,您需要除以reslength
。
我也不认为您正在正确计算Excel文件的平均时长:
240 + 21 = 261 (time 1 total seconds)
1260 + 4 = 1264 (time 2 total seconds)
--------------------
1264 + 261 = 1525 (total seconds for both times)
1525 / 2 = 762.5 (average duration in seconds)
762.5 = 12 minutes and 42.5 seconds
$(document).ready(function () {
var pad = function (num) { return ("0" + num).slice(-2); }
var totalSeconds = 0;
var reslength = $(".totalColumn").length;
$(".totalColumn").each(function () {
var currentDuration = $(this).text();
currentDuration = currentDuration.split(":");
var hrs = parseInt(currentDuration[0]);
var min = parseInt(currentDuration[1]);
var sec = parseInt(currentDuration[2]);
var currDurationSec = sec + (60 * min) + (60 * 60 * hrs);
totalSeconds += currDurationSec;
});
totalSeconds = totalSeconds / reslength;
var hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
var minutes = Math.floor(totalSeconds / 60);
var seconds = totalSeconds % 60;
$(".showResTime").text(pad(hours) + ":" + pad(minutes) + ":" + Math.ceil(seconds));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tg">
<tbody>
<tr>
<th class="tg-0lax">Time 1</th>
<td class="totalColumn">00:04:21</td>
</tr>
<tr>
<th class="tg-0lax">Time 2</th>
<td class="totalColumn">00:21:04</td>
</tr>
<tr>
<th class="tg-0lax">Time 3</th>
<td class="totalColumn">00:21:03</td>
</tr>
</tbody>
</table>
<h1 class="showResTime"></h1>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。