如何优化此功能并删除代码行?

时间:2019-07-10 09:21:34

标签: javascript typescript

我有这个函子,如何使用Object.keys(arr)删除代码行或进行优化来优化这个函子?

convertTime(diffTime): object {
    let timer = {
      days: Math.floor(diffTime / (1000 * 60 * 60 * 24)),
      hours: Math.floor((diffTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
      minutes: Math.floor((diffTime % (1000 * 60 * 60)) / (1000 * 60)),
      second: Math.floor((diffTime % (1000 *60) /(1000))),
    }
    if (timer.days <= 9) {
      timer.days.toString() === '0' + timer.days;
    }
    if (timer.hours <= 9) {
      timer.hours.toString() === '0' + timer.hours;
    }
    if (timer.minutes <= 9) {
      timer.minutes.toString() === '0' + timer.minutes;
    }
    if (timer.second <= 9) {
      timer.second.toString() === '0' + timer.second;
    }
    return timer;
  }

2 个答案:

答案 0 :(得分:1)

有一个用于将字符串填充到所需长度的函数:String.prototype.padStart。随便

    return {
      days: Math.floor(diffTime / (1000 * 60 * 60 * 24)).toString().padStart(2, '0'),
      hours: Math.floor((diffTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString().padStart(2, '0'),
      minutes: Math.floor((diffTime % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0'),
      second: Math.floor((diffTime % (1000 *60) /(1000))).toString().padStart(2, '0'),
    }

答案 1 :(得分:0)

我认为使用Object.keys()她是:

convertTime(diffTime): object {
    let timer = {
      days: Math.floor(diffTime / (1000 * 60 * 60 * 24)),
      hours: Math.floor((diffTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
      minutes: Math.floor((diffTime % (1000 * 60 * 60)) / (1000 * 60)),
      second: Math.floor((diffTime % (1000 *60) /(1000))),
    }
    Object.keys(timer).forEach(key => {
        if (timer[key] <= 9) {
            timer[key].toString() === '0' + timer[key];
        }
    });
    return timer;
}

(假设这些if做任何事情,正如@CertainPerformance所说,我对此表示怀疑,我认为这不是最好的解决方案,@ mbojko的答案更好,但这正是您的同事所寻找的)