switch

Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

La sentencia switch evalúa una expresión, comparando la expresión con un conjunto de  valores predefinidoes, y ejecuta comandos según el caso.

Syntax

switch (expresion) {
  case valor1:
    //Sentencias ejecutadas cuando el resultado de expresion coincide con valor1
    [break;]
  case valor2:
    //Sentencias ejecutadas cuando el resultado de expresion coincide con valor2
    [break;]
  ...
  case valorN:
    //Sentencias ejecutadas cuando el resultado de expresion coincide con valorN
    [break;]
  default:
    //Sentencias_def ejecutadas cuando no ocurre una coincidencia con los anteriores casos
    [break;]
}
expresion
Es una expresión que es comparada con el valor de cada instancia case.
case valorN
Es un valor a compar con la expresion.
sentenciasN
Son porciones de código que se ejecutarán únicamente en el caso que la expresión coincida con el valorN associado a la sección case.
sentencias_def
Son porciones de código que se ejecutarán si ningun valorN coincide con expresion.

Descripción

Si ocurre una coincidencia, el programa ejecuta las sentencias asociadas correspondientes. Si la expresión coincide con múltiples entradas, la primera será la seleccionada, incluso si las mayúsculas son tenidas en cuenta.

The program first looks for a case clause whose expression evaluates to the same value as the input expression (using strict comparison, ===) and then transfers control to that clause, executing the associated statements. If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not need to be so.

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

Ejemplos

Usando switch

In the following example, if expr evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program breaks out of switch and executes the statement following switch. If break were omitted, the statement for case "Cherries" would also be executed.

switch (expr) {
  case "Oranges":
    console.log("Oranges are $0.59 a pound.");
    break;
  case "Apples":
    console.log("Apples are $0.32 a pound.");
    break;
  case "Bananas":
    console.log("Bananas are $0.48 a pound.");
    break;
  case "Cherries":
    console.log("Cherries are $3.00 a pound.");
    break;
  case "Mangoes":
  case "Papayas":
    console.log("Mangoes and papayas are $2.79 a pound.");
    break;
  default:
    console.log("Sorry, we are out of " + expr + ".");
}

console.log("Is there anything else you'd like?");

¿Qué pasa si olvide un break?

Si olvidaste un break, el script se ejecutara desde donde se cumple la condición y seguirá ejecutándose independientemente si se cumple o no la condición. Ver ejemplo aquí:

var foo = 0;
switch (foo) {
  case -1:
    console.log('negative 1');
    break;
  case 0: // foo is 0 so criteria met here so this block will run
    console.log(0)
    // NOTE: the forgotten break would have been here
  case 1: // no break statement in 'case 0:' so this case will run as well
    console.log(1);
    break; // it encounters this break so will not continue into 'case 2:'
  case 2:
    console.log(2);
    break;
  default:
    console.log('default');
}

Methods for multi-criteria case

Source for this technique is here:

Switch statement multiple cases in JavaScript (Stack Overflow)

Multi-case - single operation

This method takes advantage of the fact that if there is no break below a case statement it will continue to execute the next case statement regardless if the case meets the criteria. See the section title "What happens if I forgot a break?"

This is an example of a single operation sequential switch statement, where four different values perform exactly the same.

var Animal = 'Giraffe';
switch (Animal) {
  case 'Cow':
  case 'Giraffe':
  case 'Dog':
  case 'Pig':
    console.log('This animal will go on Noah\'s Ark.');
    break;
  case 'Dinosaur':
  default:
    console.log('This animal will not.');
}

Multi-case - chained operations

This is an example of a multiple-operation sequential switch statement, where, depending on the provided integer, you can receive different output. This shows you that it wil traverse in the order that you put the case statements, and it does not have to be numerically sequential. In JavaScript, you can even mix in definitions of strings into these case statements as well.

var foo = 1;
var output = 'Output: ';
switch (foo) {
  case 10:
    output += 'So ';
  case 1:
    output += 'What ';
    output += 'Is ';
  case 2:
    output += 'Your ';
  case 3:
    output += 'Name';
  case 4:
    output += '?';
    console.log(output);
    break;
  case 5:
    output += '!';
    console.log(output);
    break;
  default:
    console.log('Please pick a number from 0 to 6!');
}

Output from this example:

Value Log text
foo is NaN or not 1, 2, 3, 4, 5 or 10 Please pick a number from 0 to 6!
10 Output: So What Is Your Name?
1 Output: What Is Your Name?
2 Output: Your Name?
3 Output: Name?
4 Output: ?
5 Output: !

Specifications

Specification Status Comment
ECMAScript 3rd Edition Standard Initial definition.
Implemented in JavaScript 1.2
ECMAScript 5.1 (ECMA-262)
The definition of 'switch statement' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'switch statement' in that specification.
Standard  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

See also

Etiquetas y colaboradores del documento

 Colaboradores en esta página: Cubo, esmarti, christpher_c
 Última actualización por: Cubo,