In JavaScript, there are two different kind of loops:
- for - loops through a block of code a specified number of times
- while - loops through a block of code while a specified condition is true
The for Loop
Example
<html><body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
The while Loop
Example
<html><body>
<script type="text/javascript">
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
</script>
</body>
</html>
The do...while Loop
Example
<html><body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);
</script>
</body>
</html>
JavaScript For...In Statement
The for...in statement loops through the elements of an array or through the properties of an object.Syntax
for (variable in object){
code to be executed
}
Note: The code in the body of the for...in loop is executed once for each element/property.
Note: The variable argument can be a named variable, an array element, or a property of an object.
Example
Use the for...in statement to 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>
No comments:
Post a Comment
Please write your view and suggestion....