簡體   English   中英

我將如何將此三元運算編寫為條件語句?

[英]How would I write this ternary operation as a conditional statement?

嗨,我想知道如何將以下三元運算編寫為常規條件語句。 如果有人能讓我知道這將不勝感激,這是代碼:

h1.textContent = "Time : " + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);

它會是這樣的:

var text = "Time : ";
if (minutes){
    if (minutes > 9){
        text += minutes;
    }
    else{
        text += "0" + minutes;
    }
}
else{
    text += "00";
}
text += ":";
if (seconds > 9){
    text += seconds;
}
else{
    text += "0" + seconds;
}
h1.textContent = text;

就個人而言,我寧願堅持使用三元在此處輸入圖片說明

一個簡單的“條件語句”替代方案

var minutesS = minutes;
if (minutes < 10) minutesS = '0' + minutes;

var secondsS = seconds;
if (seconds < 10) seconddS = '0' + seconds;

h1.textContent = "Time : " + minutesS + ":" + secondsS;

您可以采用一個函數和一些字符串方法。

function twoDigits(value) {
    return ('00' + value.toString()).slice(-2);
}


h1.textContent = "Time : " + twoDigits(minutes) + ":" + twoDigits(seconds);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM