Use For to loop through different HTML headers
<html>
<body>
<script type="text/JavaScript">
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">This is header " + i);
document.write("</h" + i + ">");
}
</script></body></html> |
For...In
Used to loop through elements of an array or properties of an object.
- The code in the body of the for ... in loop is executed once for each element/property.
Syntax
for (variable in object)
{
code to be executed
} |
The variable argument can be a named variable, an array element, or a property of an object.
Loop Through an Array
<html>
<body>
<script type="text/JavaScript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars){document.write(mycars[x] + "<br />");}
</script>
</body>
</html> |
The while loop
The while loop is used when you want the loop to execute and continue executing while the specified condition is true.
while (var<=endvalue)
{
code to be executed
} |
While Loop
<html>
<body>
<script type="text/JavaScript">
var i=0;
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html> |
Result
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10 |
Break
<html>
<body>
<script type="text/JavaScript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3){break;}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html> |
The number is 0
The number is 1
The number is 2 |
Continue: break the current loop and continue with the next value.
<html>
<body>
<script type="text/JavaScript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3){continue;}
document.write("The number is " + i);
document.write("<br />");
}
</script></body></html> |
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10 |
|