3

我正在使用 Phonegap 和 JQuery 构建一个应用程序。

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

    HH:MM:SS.mm

列表中有许多“零”时间,例如 '00:00:00.00' iphonegap、javascript 消除使用..

    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');

这样我就得到了最快的时间,而且只有那些有价值的时间。

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

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

=    00:00:04.00

提前致谢 :)

4

4 回答 4

2

如果您还要有毫秒值并且想要考虑它们,则将时间转换为毫秒。现在,将它们相加并除以记录数。否则,将所有内容转换为秒并找到平均值 - 当然,您会在几秒内得到答案。

如果花一点时间考虑一下,转换非常简单。以下是转换方法。

以毫秒为单位:

function convertToMS(timeStr) {      // timeStr in format 'HH:MM:SS.mm'
    var I = parseInt;  // for brevity
    var t = timeStr,
        h = I( t.substr(0,2) ),
        m = I( t.substr(3,2) ),
        s = I( t.substr(6,2) ),
        ms = I( t.substr(9,2) );

    return h * 3600000 + m * 60000 + s * 1000 + ms;
}

到秒:

function convertToS(timeStr) {      // timeStr in format 'HH:MM:SS[.mm]'  -- .mm is ignored.
    var I = parseInt;  // for brevity
    var t = timeStr,
        h = I( t.substr(0,2) ),
        m = I( t.substr(3,2) ),
        s = I( t.substr(6,2) );

    return h * 3600 + m * 60 + s;
}

转换完成后,将它们相加并找到平均值。

更新: 为了转换回“HH:MM:SS.mm”格式,我们将时间改回“块”的小时、分钟、秒和(如果适用)毫秒。

function chunkifyFromSec(time) {  // time in s
    var t = "",
        h = Math.floor(time / 3600),
        m = Math.floor( (t - (h * 3600)) / 60 ),
        s = t - (h * 3600) - (m * 60);
    return {
        HH: h, MM: m, SS: s, mm: 0
    };
}
function chunkifyFromMS(time) {   // time in ms
    var t = "",
        h = Math.floor(time / 3600000),
        m = Math.floor( (t - (h * 3600000)) / 60000 ),
        s = Math.floor( (t - (h * 3600000) - (m * 60000)) / 1000 ),
        mm = t - (h * 3600000) - (m * 600000) - (s * 1000);
    return {
        HH: h, MM: m, SS: s, mm: mm
    };
}

然后,我们使用以下命令以 'HH:MM:SS.mm' 格式返回字符串:

function toTimeStr(chunks) {
    return
           (chunks.HH < 0 ? '0' : '') + chunks.HH + ":"
           += (chunks.MM < 0 ? '0' : '') + chunks.MM + ":"
           += (chunks.SS < 0 ? '0' : '') + chunks.SS + "."
           += (chunks.mm < 0 ? '0' : '') + chunks.mm
}
于 2012-05-06T10:54:03.537 回答
2
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());

演示

于 2012-05-06T12:01:42.107 回答
1

我对 Javascript 没有太多经验,所以我可能有一些语法错误,但我认为你可以做类似的事情

var i = 0;
var totalTime = 0.0;
for (i=0; i < scores.length; i++) {
    var hours = parseFloat(scores[i].substring(0, 2)); //get numeric value for hours
    var minutes = parseFloat(scores[i].substring(3,5)); //get numeric value for minutes
    var seconds = parseFloat(scores[i].substring(6)); //get numeric for the seconds

    var time = ((hours * 60) + minutes) * 60 + seconds; //60 minutes in an hour, 60 seconds in a minute
    totalTime += time;
}

var avgTime = totalTime/scores.length;

var avgHours = Math.floor(avgTime / 3600); //60*60
var avgHoursStr = String(avgHours);

var avgMinutes = Math.floor((avgTime % 3600) / 60); //mod to get rid of the hours
var avgMinutesStr = String(avgMinutes);

var avgSeconds = avgTime - avgHours*3600 - avgMinutes*60; //get the remainder. Can't use mod due to decimal
var avgSeconds = String(avgSeconds);

//Concat strings. Add the ":" spacers. Where necessary, add leading 0
var avgStr = (avgHoursStr.length > 1 ? "" : "0") + avgHoursStr + ":" + (avgMinutesStr.length > 1 ? "" : "0") + avgMinuteStr + ":" + avgSecondsStr;

[编辑 - 感谢 Parth Thakkar 指出我的问题]

于 2012-05-06T11:10:43.917 回答
0

以毫秒或秒为单位返回答案:

var times = ["00:00:03.00", "00:00:05.00", "00:00:02.00", "00:00:06.00"];

function averageTimes(times,unit) {
    if (!times) {
        return false;
    }
    else {
        var totalMilliseconds = 0, hours, minutes, seconds, milliseconds, parts;
        for (var i = 0, len = times.length; i < len; i++) {
            parts = times[i].split(':');
            hours = parseInt(parts[0], 10) * 3600000;
            minutes = parseInt(parts[1], 10) * 60000;
            seconds = parseInt(parts[2].split('.')[0], 10) * 1000;
            milliseconds = parseInt(parts[2].split('.')[1], 10);
            totalMilliseconds += (hours + minutes + seconds + milliseconds);
        }
        if (!unit || unit.toLowerCase() == 'ms'){
            return totalMilliseconds/times.length + ' milliseconds';
        }
        else if (unit.toLowerCase() == 's') {
            return (totalMilliseconds/1000)/times.length + ' seconds';
        }

    }
}

// parameters:
// times: an array of times in your supplied format, 'HH:MM:SS:mm',
// unit: a string ('ms' or 's'), denoting whether to return milliseconds or seconds.
var average = averageTimes(times,'s');
console.log(average);​

JS 小提琴演示

参考:

于 2012-05-06T11:08:56.630 回答