HTML and CSS Reference
In-Depth Information
EXAMPLE 6.4 ( CONTINUED )
<script type="text/javascript">
<!--
1
var day_of_week=Math.floor((Math.random()* 7)+1);
// Get a random number between 1 and 7
// Monday is 1, Tuesday is 2, etc.
2
switch(day_of_week){
3
case 1:
case 2:
case 3:
case 4:
4
alert("Business hours Monday through Thursday are from
9am to 10pm");
5
break;
case 5:
alert("Business hours on Friday are from 9am to 6pm");
break;
case 6:
alert("Business hours on Saturday are from
11am to 3pm");
break;
6
default:
alert("We are closed on Sundays and holidays");
7
break;
8
}
//-->
</script>
</body>
</html>
EXPLANATION
1
The random number function generates a random number between 1 and 7 inclu-
sive when the script is executed. The random number is stored in a variable called
day_of_week .
2
The day_of_week value of the switch expression is matched against the values of
each of the case labels below.
3
The first case that is tested is 1 . If the random number is 1, the message “ Business
hours Monday through Thursday are from 9am to 10pm ” will be displayed in the
alert dialog box. The same is true for case 2, 3, and 4.
4
This statement is executed if case 1, 2, 3, or 4 are matched. Note there are no break
statements associated with any of these 4 case statements. Program control just
drops from one case to the next, and if cases 1, 2, 3, or 4 are not matched, execu-
tion control goes to the next case (case 5) for testing.
5
The break statement causes program control to continue after line 8. Without it,
the program would continue executing statements into the next case , “yellow” ,
and continue doing so until a break is reached or the switch ends—and we don't
want that. The break statement sends control of the program to line 8.
Search WWH ::




Custom Search