Loop will execute a statement number of time depends on a
condition
JS supports four types of looping structures
1. While
If will execute the statement n-number of times each time
verify first condition and then execute statement.
<html>
<head>
<script
language="javascript">
document.write("<h1>While</h1>");
document.write("<select
style='width:200px;'>");
var
i=1;
while(i<=30){
document.write("<option>"+i+"</option>");
i++;
}
document.write("</select>");
</script>
</head>
<body>
</body>
</html
2. Do While
It will execute the statement first and then verify the
condition for first iteration only but remaining iterations executes depends on
condition.
<html>
<head>
<script
language="javascript">
document.write("<h1>While</h1>");
document.write("<ul>");
var
i=1;
do{
document.write("<li>"+i+"</li>");
i++;
}while(i<=12)
document.write("</ul>");
</script>
</head>
<body>
</body>
</html>
3. For
It is also similar to while loop but it will work only for
fixed iterations that means we need to specify starting position and ending
position
<html>
<head>
<script
language="javascript">
document.write("<h1>While</h1>");
document.write("<table
border='1' align='center' width='300px'>");
for(i=1900;i<=2016;i++){
document.write("<tr>");
document.write("<td>"+i+"</td>");
document.write("<td>name</td>");
document.write("<td>email</td>");
document.write("</tr>");
}
document.write("</table>");
</script>
</head>
<body>
</body>
</html>
4. For-in
It is a special loop for only JS to iterate arrays
No comments:
Post a Comment