The objective of
a switch statement is to give an expression to evaluate and
several different statements to execute based
on the value
of the expression.
The interpreter checks each case
against the value
of the expression until a match is found. If nothing matches,
a default condition will be used.
switch(expression)
{
case condition 1:
statement(s)
break;
case condition 2:
statement(s)
break;
..........
case condition n:
statement(s)
break;
default: statements(s)
}
The break statements indicate the end of a particular case.
<html>
<body>
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
{
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
</body>
</html>
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript switch</h2>
<p id="switch"></p>
<script>
var day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("switch").innerHTML = "Today is " + day;
</script>
</body>
</html>
No comments:
Post a Comment