La sentencia break, que se utiliza para salir antes de tiempo de un bucle.
Se puede usar una etiqueta con un descanso para controlar el flujo con mayor precisión. Una etiqueta es simplemente un identificador seguido de dos puntos (:) que se aplica a una declaración o un bloque de código.
Nota: no debe haber ninguna otra declaración entre el nombre de una etiqueta y el bucle asociado.
Ejemplo-1: Salir del bucle anidado
<!DOCTYPE html> <html> <head> <title> Break Nested For loop </title> </head> <body> <script type="text/javascript"> <!-- document.write( "Entering the Geeks For Geeks!<br /> "); for (var i = 0; i < 5; i++) { document.write( "For Upper Level in GfG : " + i + "<br />"); document.write("<br />") for (var j = 0; j < 5; j++) { // Break from the inner loop if (j == 3) break; document.write( "For Deeper Level in GfG : " + j + " <br />"); } // Break from the outer loop if (i == 3) break; } document.write("Exiting the Geeks For Geeks!<br /> "); </script> </body> </html
Producción:
Entering the Geeks For Geeks! For Upper Level in GfG : 0 For Deeper Level in GfG : 0 For Deeper Level in GfG : 1 For Deeper Level in GfG : 2 For Upper Level in GfG : 1 For Deeper Level in GfG : 0 For Deeper Level in GfG : 1 For Deeper Level in GfG : 2 For Upper Level in GfG : 2 For Deeper Level in GfG : 0 For Deeper Level in GfG : 1 For Deeper Level in GfG : 2 For Upper Level in GfG : 3 For Deeper Level in GfG : 0 For Deeper Level in GfG : 1 For Deeper Level in GfG : 2 Exiting the Geeks For Geeks!
Ejemplo-2: Salir del bucle anidado usando Etiquetas .
<!DOCTYPE html> <html> <head> <title> Break Nested For loop Using Labels </title> </head> <body> <script type="text/javascript"> <!-- document.write("Entering the Geeks for Geeks!<br /> "); upperloop: // This is the label name for (var i = 0; i < 5; i++) { document.write( "For Upper Level in GfG : " + i + "<br />"); document.write("<br />"); deeperloop: for (var j = 0; j < 5; j++) { // Break from the inner loop if (j > 3) break; // Do the same thing if (i == 2) break deeperloop; // Break from the outer loop if (i == 3) break upperloop; document.write("For Deeper Level in GfG: " + j + " <br />"); } } document.write("Exiting the Geeks For Geeks!<br /> "); </script> </body> </html>
Producción:
Entering the Geeks for Geeks! For Upper Level in GfG : 0 For Deeper Level in GfG: 0 For Deeper Level in GfG: 1 For Deeper Level in GfG: 2 For Deeper Level in GfG: 3 For Upper Level in GfG : 1 For Deeper Level in GfG: 0 For Deeper Level in GfG: 1 For Deeper Level in GfG: 2 For Deeper Level in GfG: 3 For Upper Level in GfG : 2 For Upper Level in GfG : 3 Exiting the Geeks For Geeks!
Publicación traducida automáticamente
Artículo escrito por ravikishor y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA