Home  >  Article  >  Web Front-end  >  Javascript basic tutorial - for loop_basic knowledge

Javascript basic tutorial - for loop_basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:19:311160browse

Using a loop is convenient if you want to run the same code over and over again, with different values ​​each time.

Copy code The code is as follows:

document.write(cars[0] "
");
document.write(cars[1] "
");
document.write(cars[2] "
");
document.write(cars[3] "
");
document.write(cars[4] "
");
document.write(cars[5] "
");

But let’s write it like this

Copy code The code is as follows:

for (var i=0; i {
document.write(cars[i] "
");
}

Example: Output numbers from 1-100

Copy code The code is as follows:

for(var i=0;i <=100;i )
{
document.write(i "
")
}

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.

Copy code The code is as follows:

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;

The above is all about the for loop in JavaScript. I hope you guys like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn