break
dice JavaScript per fermare valutare casi nel blocco switch
. L'esecuzione del codice continua dopo la parentesi chiusa switch
. L'istruzione return
nel codice di esempio impedirà in effetti di superare qualsiasi cosa, comprese le altre istruzioni case
e qualsiasi altra cosa che segue il blocco switch
.
Ho messo una dichiarazione break
in ogni caso per abitudine. Se ho scritto un caso senza un break
allora potrei copiare e incollare blocchi di codice in giro per il futuro e la mancanza di una dichiarazione break
sarebbe diventato un bug in questo modo:
function whereLivesA(species){
switch(species){
case 'worms':
// Relying on return to prevent further code execution within the switch
// block works but is ~bad~ smelly (according to plato :D)
var habitat = 'dirt'
return (species + ' live in ' + habitat);
case 'bees':
var habitat = 'hive';
break;
}
// Stuff to do after the switch statement (unless you returned already)
var str = species+' live in '+habitat;
return str;
}
console.log('whereLivesA');
console.log(whereLivesA("worms"));
console.log(whereLivesA("bees"));
/* Output:
whereLivesA
worms live in dirt
bees live in hive
*/
function whereLivesB(species){
switch(species){
case "worms":
// what if future code changes remove `return` and don't add `break`?
// return (species + ' live in ' + habitat)
var habitat = 'dirt';
// break;
case "bees":
var habitat = 'hive'
break;
}
// Stuff to do after the switch statement (unless you returned already)
var str = species+' live in '+habitat;
return str;
}
console.log('whereLivesB');
console.log(whereLivesB("bees"));
console.log(whereLivesB("worms"));
/* Output:
whereLivesB
bees live in hive
worms live in hive
*/
function whereLivesCorrect(species){
switch(species){
case "worms":
var habitat = 'dirt';
break;
case "bees":
var habitat = 'hive'
break;
}
// Stuff to do after the switch statement (unless you returned already)
var str = species+' live in '+habitat;
return str;
}
console.log('whereLivesCorrect');
console.log(whereLivesCorrect("bees"));
console.log(whereLivesCorrect("worms"));
/* Output:
whereLivesCorrect
bees live in hive
worms live in dirt
*/
JS neofiti: se non lo fai vuoi salvarlo in un file ed eseguire node filename
, puoi premere F12 e incollare questo script o altri script autonomi nella console del tuo browser per eseguirlo.
Se si utilizza node.js, è inoltre possibile digitare node
da una riga comandi per avviare una console node
e incollarla lì.
Questo è _probably_ solo per evitare contro gli errori che deriverebbero da copiare/incollare e/o haphhazardly modifica che il codice in futuro . Sembra una buona rete di sicurezza per me. – jahroy
Dato i rientri, potrebbe essere solo una scelta stilistica - usando il 'break' come la fine di un suggerito [blocco] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/dichiarazioni/blocco). Ma il 'break' è un codice irraggiungibile dopo un'istruzione' return'. Quindi, non farà nulla; ma non farà del male a nessuno. –