Using a loop is convenient if you want to run the same code over and over again, with different values each time.
But let’s write it like this
Example: Output numbers from 1-100
for is a pre-test loop, and can initialize variables before the loop and define the code to be executed after the loop. Its syntax is as follows
for(inintialization;expression;psot=loop-expression)statement
The execution process is as follows:
1. Execute initialization statement
2. Determine whether expression is true. If so, continue, otherwise terminate the entire loop.
3. Execute the statement code of the loop body
4. Execute post-loop-expression code
5. Return to step 2
The most commonly used form of for loop is for(var i=0; i It means that the loop is executed a total of n times, which is very suitable for operations with a known number of loops. The above is all about the for loop in JavaScript. I hope you guys like it.
var aNumbers = new Array();
var sMessage = "You entered:n";
var iTotal = 0;
var vUserInput;
var iArrayIndex = 0;
do{
vUserInput = prompt("Enter a number, or exit with '0'","0");
aNumbers[iArrayIndex] = vUserInput;
iArrayIndex ;
iTotal = Number(vUserInput);
sMessage = vUserInput "n";
}while(vUserInput != 0) //Exit the loop body when the input is 0 (default value)
sMessage = "Total:" iTotal;
Document.getElementById("xxx").innerHTML=sMessage;