在时间输入类型中插入 SubString

我有一个时间计算器,它以下列格式返回时间的输入类型:hh/mm/ss


目前显示如下:


Let time = "03:00:00"

当我执行计算函数时,它返回“3:0:0”并删除“0”。


如何将其更改为 03:00:00?仅当 h/m/s 小于 10 时才必须添加“0”。


如果需要,这是我的计算函数。该函数返回数组的时间总和:


let testOne = ["02:00:00", "01:00:00", "01:00:00"]


function test () {

let calTotalHours = testOne.map(t => t.split(':')).reduce((arr,item,index)=>{


    arr[0]+= parseFloat(item[0]);

    arr[1]+= parseFloat(item[1]);

    arr[2]+= parseFloat(item[2]);


    if(arr[2]>=60) {

        arr[1]++;

        arr[2]%=60;

    }

    if(arr[1]>=60) {

        arr[0]++;

        arr[1]%=60;

    }

    return arr;

},[0,0,0])

    .join(':')

    console.log(calTotalHours)

}


慕斯709654
浏览 151回答 3
3回答

临摹微笑

您需要在 reduce 之后添加零,因为 reduce 仍在计算时间。我.map在计算后添加了一个以获取每个时间值,然后检查值是否小于 10:.map((v) => (v < 10) ? v = "0" + v : v)let testOne = ["02:00:00", "01:00:00", "01:00:00"]function test() {  let calTotalHours = testOne.map(t => t.split(':')).reduce((arr, item, index) => {    arr[0] += parseFloat(item[0]);    arr[1] += parseFloat(item[1]);    arr[2] += parseFloat(item[2]);    if (arr[2] >= 60) {      arr[1]++;      arr[2] %= 60;    }    if (arr[1] >= 60) {      arr[0]++;      arr[1] %= 60;    }    return arr;  }, [0, 0, 0]).map((v) => (v < 10) ? v = "0" + v : v).join(':')  console.log(calTotalHours)}test()

茅侃侃

你可以做这样的事情来获得你想要的padStart()功能let testOne = ["02:00:00", "01:00:00", "01:00:00"]function test() {&nbsp; let calTotalHours = testOne.map(t => t.split(':')).reduce((arr, item, index) => {&nbsp; &nbsp; &nbsp; arr[0] += parseFloat(item[0]);&nbsp; &nbsp; &nbsp; arr[1] += parseFloat(item[1]);&nbsp; &nbsp; &nbsp; arr[2] += parseFloat(item[2]);&nbsp; &nbsp; &nbsp; if (arr[2] >= 60) {&nbsp; &nbsp; &nbsp; &nbsp; arr[1]++;&nbsp; &nbsp; &nbsp; &nbsp; arr[2] %= 60;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; if (arr[1] >= 60) {&nbsp; &nbsp; &nbsp; &nbsp; arr[0]++;&nbsp; &nbsp; &nbsp; &nbsp; arr[1] %= 60;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return arr;&nbsp; &nbsp; }, [0, 0, 0])&nbsp; &nbsp; .map((num) => num.toString().padStart(2, 0)) //add 0 to each value here if they are less than 10&nbsp; &nbsp; .join(':');&nbsp; console.log(calTotalHours);}test();

富国沪深

您可以在加入阵列之前尝试使用 .padStart() on:.map(num&nbsp;=>&nbsp;num.toString().padStart(2,&nbsp;'0'))这将填充长度小于 2 的前导 0
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript