Home>

You can use multiple if ... else if statements, as in the previous chapter,Perform multi-way branching.However, this is not always the best solution,Especially when all branches depend on the value of a single variable.

Starting with javascript1.2, you can use it to handle exactly this situation,Use a switch statement, which does this more efficiently,If not use the if ... else if statement repeatedly.

grammar

The basic syntax of a switch statement gives an expression to evaluate the calculation of several different statements based on the value of that expression.The interpreter checks every case of the value of the expression,Until a match is found.If there is no match,The 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:statement (s)
}

The break statement indicates that the interpreter ends under certain circumstances.If they are omitted,The interpreter will continue to execute each statement in each of the following cases.

We will explain the break statement in the loop control chapter.

example:

The following example illustrates a basic while loop:

<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 />");
      break;
 default:document.write ("unknown grade<br />")
}
document.write ("exiting switch block");
//->
</script>

This will produce the following results:

entering switch block
good job
exiting switch block

example:

Consider such a situation,Without the break statement:

<script type="text/javascript">
<!-
var grade="a";
document.write ("entering switch block<br />");
switch (grade)
{
 case "a":document.write ("good job<br />");
 case "b":document.write ("pretty good<br />");
 case "c":document.write ("passed<br />");
 case "d":document.write ("not so good<br />");
 case "f":document.write ("failed<br />");
 default:document.write ("unknown grade<br />")
}
document.write ("exiting switch block");
//->
</script>

This will produce the following results:

entering switch block
good job
pretty good
passed
not so good
failed
unknown grade
exiting switch block
  • Previous Php using ob_flush cannot output every one second
  • Next Detailed extension () and fnextend () methods in jQuery