Basic Javascript tutorial-break and continue statements, basic tutorial-continue
The break and continue statements provide stricter Process Control for code execution in the loop. The break statement can immediately exit the loop to prevent any code in the loop body from being executed again. The continue statement only exits the current loop and allows the next loop based on the control expression.
Break
Copy codeThe Code is as follows:
<Script language = "javascript">
Var aNumbers = new Array ();
Var sMessage = "you entered: <br> ";
Var iTotal = 0;
Var vUserInput;
Var iArrayIndex = 0;
Do {
VUserInput = Number (prompt ("enter a Number, or '0' to exit", "0 "));
If (isNaN (vUserInput )){
Document. write ("incorrect input. Enter a number and '0' to exit <br> ");
Break; // enter an error to exit the entire do loop.
}
ANumbers [iArrayIndex] = vUserInput;
IArrayIndex ++;
} While (vUserInput! = 0) // exit the loop body when the input is 0 (default)
// Common methods for Traversing arrays through a for Loop:
For (var I = 0; I <aNumbers. length; I ++ ){
ITotal + = Number (aNumbers [I]);
SMessage + = aNumbers [I] + "<br> ";
}
SMessage + = "Total:" + iTotal;
Document. write (sMessage );
</Script>
Continue
Copy codeThe Code is as follows:
<Script language = "javascript">
Var aNumbers = new Array ();
Var sMessage = "you entered: <br> ";
Var iTotal = 0;
Var vUserInput;
Var iArrayIndex = 0;
Do {
VUserInput = Number (prompt ("enter a Number, or '0' to exit", "0 "));
If (isNaN (vUserInput )){
Alert ("input error, please enter a number, '0' to exit ");
Continue; // If the input is incorrect, the current loop is exited and the next loop continues.
}
ANumbers [iArrayIndex] = vUserInput;
IArrayIndex ++;
} While (vUserInput! = 0) // exit the loop body when the input is 0 (default)
// Common methods for Traversing arrays through a for Loop:
For (var I = 0; I <aNumbers. length; I ++ ){
ITotal + = Number (aNumbers [I]);
SMessage + = aNumbers [I] + "<br> ";
}
SMessage + = "Total:" + iTotal;
Document. write (sMessage );
</Script>
Do you know the differences and connections between the two statements?