2017-08-02 70 views
0

大家好我的工作時鐘計時器我寫在角碼的代碼它做工非常精細角2加零爲字符串之前數不起作用

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

輸出是正確的,但在我想在幾秒鐘或幾分鐘或幾小時前加零,如果他們是< 10我寫這個sec = "0" + sec它告訴我the String Type Is Not assignable to sec謝謝你。

+1

創建一個單獨的填充功能(如[這個答案](https://stackoverflow.com/a/40717803/1229023)),那麼就內使用字符串模板(如'$ {pad(hour)}:$ {pad(min)} ...'等) – raina77ow

回答

0

嘗試這樣:

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