简体   繁体   English

我将如何将此三元运算编写为条件语句?

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

Hi I would like to know how to write the following ternary operation as a regular conditional statement.嗨,我想知道如何将以下三元运算编写为常规条件语句。 If someone could let me know that would be greatly appreciated, here is the code:如果有人能让我知道这将不胜感激,这是代码:

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

It'd go something like this:它会是这样的:

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;

Personally, I'd rather stick with the ternary就个人而言,我宁愿坚持使用三元在此处输入图片说明

A simple "conditional statements" alternative一个简单的“条件语句”替代方案

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

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

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

You could take a function and some string methods.您可以采用一个函数和一些字符串方法。

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