使用JavaScript平均时间 [英] Averaging Times using Javascript

查看:79
本文介绍了使用JavaScript平均时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Phonegap和JQuery构建应用程序.

I am building an app using Phonegap and JQuery.

该应用程序(使用window.localStorage)以格式存储一组时间(不超过10次).

The app stores ( using window.localStorage ) a set of times (no more than 10) in the format.

    HH:MM:SS.mm

列表中有许多零"时间,例如"00:00:00.00",其中iphonegap,javascript 消除使用..

There are a number of 'Zero' times in the list eg '00:00:00.00' which iphonegap, javascript eliminate using..

    function removeA(arr){
        var what, a= arguments, L= a.length, ax;
        while(L> 1 && arr.length){
            what= a[--L];
            while((ax= arr.indexOf(what))!= -1){
                arr.splice(ax, 1);
            }
        }
        return arr;
    }

    scores.sort();
    removeA(scores,'00:00:00.00');

这样我就可以拥有最快的时间,只有那些有价值的时间.

so that i'm left with the fastest time first, and only the times that have a value.

我需要从剩余值中得出这些时间的平均值.

I need to produce from the remaining values the average of those times.

eg:  00:00:03.00
     00:00:05.00
     00:00:02.00
     00:00:06.00

=    00:00:04.00

提前感谢:)

推荐答案

var times= [ '00:00:03.00', '00:00:05.00', '00:00:02.00', '00:00:06.00'],
    date = 0,
    result = '';
function offsetify(t){
    return t < 10 ? '0' + t : t;
}
for(var x = 0; x < times.length; x++ ) {
    var tarr = times[x].split(':');
    date += new Date(0, 0, 0, tarr[0], tarr[1], tarr[2].split('.')[0], tarr[2].split('.')[1]).getTime();   
}
var avg = new Date(date/times.length);
result = offsetify(avg.getHours()) + ':' + offsetify(avg.getMinutes()) + ':' + offsetify(avg.getSeconds()) + '.' + offsetify(avg.getMilliseconds());

演示

这篇关于使用JavaScript平均时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆