【问题标题】:angular 2 add zero as a string before number doesn't workangular 2 在数字不起作用之前添加零作为字符串
【发布时间】:2018-01-09 15:56:26
【问题描述】:

大家好,我正在研究时钟计时器,我用角码编写了代码,它工作得很好

let timer: string = "0:00:00";

startPause() {
  this.play = false;
  this.pause = true;
  let sec = 0;
  let min = 0;
  let hour = 0;

  setInterval(() => {
    if(sec === 59) {
      min++;
      sec = 0;
    }
    else if(min > 59) {
      hour++;
      min = 0;
    }
    else {
      sec++;
    }
    this.timer = `${hour}:${min}:${sec}`;
  }, 10);
}

输出是正确的,但是当我想在秒或分钟或小时之前添加零时,如果它们 sec = "0" + sec 它告诉我the String Type Is Not assignable to sec 谢谢你。

【问题讨论】:

  • 创建一个单独的填充函数(如this answer 中所述),然后在字符串模板中使用它(如${pad(hour)}:${pad(min)}... 等)

标签: javascript angular typescript


【解决方案1】:

试试这样的:

...
let strSec = String(sec);
if (sec < 10) {
    strSec = '0' + strSec;
}
... //same for hour and min
this.timer = `${strHour}:${strSec}:${strSec}`;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 2014-12-12
    • 2014-07-13
    • 2013-03-29
    相关资源
    最近更新 更多