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

问题描述 投票:-2回答:3

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

h1.textContent = "Time : " + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
javascript conditional ternary-operator
3个回答
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
投票

简单的“条件陈述”替代方案

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

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

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

0
投票

你可以采用一个函数和一些字符串方法。

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


h1.textContent = "Time : " + twoDigits(minutes) + ":" + twoDigits(seconds);
© www.soinside.com 2019 - 2024. All rights reserved.