I'll just say at the outset that I wouldn't rewrite it as a switch
. But I would definitely change it. (I'll do the switch
below, though.)
First, your "ساعت وارد شده نامعتبر است !"
case will never happen. getHours
returns a number between 0 and 23, inclusive. So there's no need to handle the case of < 0
or >= 24
.
Here's how I'd write it:
var hour = new Date().getHours();
var msg;
if (hour < 6) {
msg = "بامداد شما بخیر !";
} else if (hour < 11) {
msg = "صبح شما بخیر !";
} else if (hour < 15) {
msg = "ظهر شما بخیر !";
} else if (hour < 20) {
msg = "عصر شما بخیر !";
} else {
msg = "شب شما بخیر !";
}
print(hour);
print("------------------------");
print(msg);
Note how we're not having to write our limits in two places. There's no need for it, since we won't evaluate later else if
s if the earlier if
was true.
Now, for the actual switch
, we do something similar, using the fact that JavaScript's switch
is more powerful than in many similar-looking languages (JavaScript's switch
is basically just an if/else if
):
var hour = new Date().getHours();
var msg;
switch (true) {
case hour < 6:
msg = "بامداد شما بخیر !";
break;
case hour < 11:
msg = "صبح شما بخیر !";
break;
case hour < 15:
msg = "ظهر شما بخیر !";
break;
case hour < 20:
msg = "عصر شما بخیر !";
break;
default:
msg = "شب شما بخیر !";
break;
}
print(hour);
print("------------------------");
print(msg);
How that works: JavaScript's switch
allows the case
labels to be expressions. It evaluates each case
in source code order against the value you give in the switch
, taking the first case that matches. If no cases match, it uses the default
(regardless of where the default is in the source code).
Again: I wouldn't do that. But the question was how to do it. :-)