JavaScript - Alternar caso

Você pode usar vários if...else…ifinstruções, como no capítulo anterior, para realizar uma ramificação multiway. No entanto, nem sempre essa é a melhor solução, especialmente quando todos os ramos dependem do valor de uma única variável.

Começando com JavaScript 1.2, você pode usar um switch declaração que lida exatamente com esta situação, e o faz de forma mais eficiente do que repetida if...else if afirmações.

Fluxograma

O fluxograma a seguir explica o funcionamento de uma instrução switch-case.

Sintaxe

O objetivo de um switchinstrução é fornecer uma expressão para avaliar e várias instruções diferentes para executar com base no valor da expressão. O intérprete verifica cadacase 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: statement(s)
}

The break statements indicate the end of a particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases.

We will explain break statement in Loop Control chapter.

Example

Try the following example to implement switch-case statement.

<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 />");
               break;
            
               default:  document.write("Unknown grade<br />")
            }
            document.write("Exiting switch block");
         //-->
      </script>      
      <p>Set the variable to different value and then try...</p>
   </body>
</html>

Output

Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...

Break statements play a major role in switch-case statements. Try the following code that uses switch-case statement without any break statement.

<html>
   <body>      
      <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>      
      <p>Set the variable to different value and then try...</p>
   </body>
</html>

Output

Entering switch block
Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block
Set the variable to different value and then try...