+ 1

How can I combine two "if" into one?

This example is from the lesson about The Date object: function printTime() { var d = new Date(); var hours = d.getHours(); var mins = d.getMinutes(); var secs = d.getSeconds(); document.body.innerHTML = hours+":"+mins+":"+secs; } setInterval(printTime, 1000); I can add "0" to my numbers with: if (mins < 10) { mins = "0" + mins; } if (secs < 10) { secs = "0" + secs; } Ok, but how can I combine these two "if" into one? I don't need two "if", I would like one formula (/some "function"/) for two examples (mins & secs) at the same time.

20th Oct 2016, 9:13 AM
Marsel Gizatullin
Marsel Gizatullin - avatar
2 Respuestas
+ 4
It is fine as it is, but if you really want to, you can create a function that prepends a "0" if the argument is lower than 10, and return it. function formatFix(n) { if (n < 10) { n = "0" + n; } return (n.toString()); }
20th Oct 2016, 10:35 AM
Zen
Zen - avatar
0
@Zen, isn't the ".toString()" unnecessary? Or are you just making sure that it will return a string no matter what the input was..?
23rd Oct 2016, 3:23 PM
Andy Stutzmann