我不明白这行代码。有人可以逐字逐句解释第4行的含义吗?
hour = Math.floor(nextArrival / 3600);
min = Math.floor(nextArrival % 3600 / 60);
sec = Math.floor(nextArrival % 3600 % 60);
nextArrivalFinal2 = ((hour > 0 ? hour + ":" + (min < 10 ? "0" : "") : "") + min + ":" + (sec < 10 ? "0" : "") + sec);
如何编写它,以便在新的一天和时间为00:00:00时,它仍会显示小时所在的00。目前,第4行中的代码跳过显示小时数,如果我认为是在1以下。所以如果时间是00:05 AM,它将只显示分钟和秒而不是00小时。
答案 0 :(得分:0)
Its called a ternary operator
(expression) ? true part : false part
This is more verbose approach for your line 4
var nextArrivalFinal2 = ""
if (hours > 0) {
nextArrivalFinal2 = hour + ":";
if (min < 10)
nextArrivalFinal2 += "0"
else
nextArrivalFinal2 += ""
} else {
nextArrivalFinal2 += "";
}
nextArrivalFinal2 += min + ":";
if (sec < 10)
nextArrivalFinal2 += "0"
else
nextArrivalFinal2 += "";
nextArrivalFinal2 + sec
答案 1 :(得分:0)
This line is using the Conditional Operator
condition ? expr1 : expr2
Using only if
and else
this would give something like this
if(hour > 0){
text = hour + ":";
if(min < 10){
text += "0"
}else{
text += ""
}
text += "";
}
text += min + ":";
if(sec < 10){
text += "0";
}else{
text += "";
}
text += sec;
Obviously there are useless else
but I still show them to use every term of the conditional operator.
答案 2 :(得分:0)
The others have explained line 4 very well, but for the last part of your question, you want something like consistent formatting as hh:mm:ss
?
nextArrivalFinal2 = (hour < 10 ? "0" : "") + hour + ":" + (min < 10 ? "0" : "") + min + ":" + (sec < 10 ? "0" : "") + sec;
答案 3 :(得分:0)
//示例nextArrival = 3760(这是以秒为单位的实际时间) //小时给你的小时数:1小时= 3600秒
hour = Math.floor(nextArrival / 3600);
//获取分钟数:nextArrival % 3600
将为您提供删除小时数的秒数
min = Math.floor(nextArrival % 3600 / 60);
//这会给你秒数
sec = Math.floor(nextArrival%3600%60);
// nextArrivalFinal2 =((小时> 0?小时+“:”+(小于&lt; 10?“0”:“”):“”)+ min +“:”+(秒<10?“0”:“ “)+ sec);
您必须了解三元运算符 这是一个基本的三元运算符 a&gt; b? a:b;
如果a大于b,则取a,否则取b;
同样,在这种情况下,如果hour>0
它会打印hour + some other values of minnutes which also have a ternary operator
其他“”,如下面代码第10行所述。
之后,他们是一个+,这意味着附加到一个字符串。
那么它将打印min的值,如第12行所示+某个sec值,它将再次成为一个三元运算符
最后它将在第17行打印sec
((hour > 0
?
hour + ":" +
(min < 10
?
"0"
:
"")
:
"")
+
min + ":" + (sec < 10
?
"0"
:
"")
+ sec)