Frase switch in JavaScript

Definizione e uso

La frase switch esegue blocchi di codice in base a diverse situazioni.

La frase switch è parte della struttura condizionale di JavaScript, utilizzata per eseguire diverse operazioni in base a condizioni diverse. Utilizza switch per selezionare uno dei molti blocchi di codice da eseguire. È una soluzione perfetta per lunghe sequenze di if/else annidati.

La statement switch calcola l'espressione. Poi confronta il valore dell'espressione con il valore di ogni case all'interno della struttura. Se corrisponde, esegue il blocco di codice associato.

La statement switch viene solitamente utilizzata con la parola chiave break o default (o entrambe). Queste sono opzionali:

La parola chiave break esce dal blocco switch. Questo ferma l'esecuzione di ulteriori codici e / o test di casi all'interno del blocco. Se viene omesso break, viene eseguito il successivo blocco di codice nella statement switch.

Se non corrisponde nessun case, la parola chiave default specifica alcuni codici da eseguire. Può esserci solo una parola chiave default in un switch. Sebbene sia opzionale, si consiglia di utilizzarla perché può gestire situazioni impreviste.

Example

Esegui il blocco di codice in base all'input dell'utente:

var text;
var fruits = document.getElementById("myInput").value;
switch(fruits) {
  case "Banana":
    text = "La banana è buona!";
    break;
  case "Orange":
    text = "Non sono un fan dell'arancia.";
    break;
  case "Apple":
    text = "Ti piacciono questi mele?";
    break;
  default:
    text = "Non ho mai sentito parlare di quell'frutto...";
}

Try It Yourself

Più esempi TIY in fondo alla pagina.

Sintassi

switch(espressione) {
  case n:
    blocco di codice
    break;
  case n:
    blocco di codice
    break;
  default:
    blocco di codice predefinito
}

Valore del parametro

Parametro Descrizione
espressione Obbligatorio. Specificare l'espressione da calcolare. L'espressione viene calcolata una volta. Il valore dell'espressione viene confrontato con il valore di ogni etichetta case all'interno della struttura. Se corrisponde, viene eseguito il blocco di codice associato.

Dettagli tecnici

Versione JavaScript: ECMAScript 1

Più esempi

Example

Calcola il nome della giornata della settimana in base al numero di giornata odierna (Domenica=0, Lunedì=1, Martedì=2, ...):

var day;
switch (new Date().getDay()) {
  case 0:
    day = "domenica";
    break;
  case 1:
    day = "lunedì";
    break;
  case 2:
    day = "martedì";
    break;
  case 3:
    day = "mercoledì";
    break;
  case 4:
    day = "giovedì";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
    break;
  default:
    day = "Unknown Day";
}

Try It Yourself

Example

If today is neither Saturday nor Sunday, write a default message:

var text;
switch (new Date().getDay()) {
  case 6:
    text = "Today is Saturday";
    break; 
  case 0:
    text = "Today is Sunday";
    break; 
  default: 
    text = "Looking forward to the Weekend";
}

Try It Yourself

Example

Sometimes you may want different conditions to use the same code, or use the same default value.

Please note that in this example, cases share the same code block, and the default case does not have to be the last case in the switch block (but, if the default is not the last case in the switch block, remember to end it with a break).

var text;
switch (new Date().getDay()) {
  case 1:
  case 2:
  case 3:
  default: 
    text = "Looking forward to the Weekend";
    break; 
  case 4:
  case 5:
    text = "Soon it is Weekend";
    break; 
  case 0:
  case 6:
    text = "It is Weekend";
}

Try It Yourself

Example

Execute code blocks using switch statements based on user input from the prompt box:

var text;
var favDrink = prompt("What's your favorite cocktail drink?");
switch(favDrink) {
  case "Martini":
    text = "Excellent choice! Martini is good for your soul.";
    break;
  case "Daiquiri":
    text = "Daiquiri is my favorite too!";
    break;
  case "Cosmopolitan":
    text = "Really? Are you sure the Cosmopolitan is your favorite?";
    break;
  default:
    text = "I have never heard of that one..";
}

Try It Yourself

Browser Support

Statement Chrome IE Firefox Safari Opera
switch Supported Supported Supported Supported Supported

Related Page

Corso JavaScript:JavaScript If...Else Statement

Corso JavaScript:Espressione Switch JavaScript

Manuale di riferimento JavaScript:Espressione if/else JavaScript

Manuale di riferimento JavaScript:Espressione break JavaScript