前端剑解之求平均时间

88 阅读1分钟

给定一个时间数组,求平均时间;

function calcAvgTime1(arr) {
    const res = arr.map(item => {
        const [hours, minutes] = item.split(":").map(Number);
        return hours * 60 + minutes;
    });
    const avg = res.reduce((pre, cur) => pre + cur) / res.length;
    const hour = Math.floor(avg / 60);
    const minute = Math.round(avg % 60);
    return `${hour}:${minute}`;
}

这里还有一种更便捷(取巧)的实现方式,个人还是比较推荐下面这种,代码少

function calcAvgTime(arr) {
    let result = 0
    arr.forEach(el => {
        result += new Date('2000/01/01 ' + el).getTime()
    })
    const a = new Date(result / arr.length)
    return `${a.getHours()}:${a.getMinutes()}`
}