我如何将这个三元运算写为条件语句?

时间:2018-02-28 12:57:28

标签: javascript conditional ternary-operator

您好我想知道如何将以下三元操作编写为常规条件语句。如果有人能让我知道,我将非常感激,这里是代码:

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

3 个答案:

答案 0 :(得分:1)

它会是这样的:

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;

就个人而言,我宁愿坚持三元enter image description here

答案 1 :(得分:1)

简单的“条件陈述”替代

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

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

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

答案 2 :(得分:0)

您可以使用函数和一些字符串方法。

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


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