JavaScript for ...LOGIN

JavaScript for loop

JavaScript for loop is used to repeatedly execute a piece of code. Its syntax is as follows:

##for (expr1; expr2; expr3){ statement
}

Usually a for loop is used when the number of executions has been determined. The following example outputs 1 to 10:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
    <script type="text/javascript">
        var i=1
        for (i = 1; i <= 10; i++) {
        document.write(i + "<br />")
        }
    </script>
</head>
<body>
</body>
</html>

Running result:

12
3
4
5
6
7
8
9
10

Interpretation of for loop syntax

The first expression (expr1) is evaluated unconditionally once before the start of the loop

expr2 is evaluated before the start of each loop. If the value is TRUE, the loop continues , execute the nested loop statement; if the value is FALSE, the loop is terminated.

expr3 is evaluated (executed) after each loop

Each expression can be empty. If expr2 is empty, the loop will continue indefinitely, but the loop can be ended by break, as in the following example:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
    <script type="text/javascript">
        var i=1
        for (i = 1; ; i++) {
        if (i > 10) {
        break;
        }
        document.write(i + "<br />");
        }
    </script>
</head>
<body>
</body>
</html>

This example still outputs 1 to 10, but uses if conditional judgment. When i>10, End the cycle.

Tips

When using loop statements, we usually have to be careful not to loop infinitely and cause the program to "zombie". In addition, we must also pay attention to loop conditions (loop judgment expressions formula) to ensure that the loop results are correct.


For/In Loop

JavaScript for/in statement loops through the properties of an object:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x;
var txt="";
var person={fname:"Bill",lname:"Gates",age:56}; 
for (x in person){
txt=txt + person[x];
}
document.getElementById("demo").innerHTML=txt;
}
</script>
</body>
</html>


Next Section

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var i=1 for (i = 1; ; i++) { if (i > 10) { break; } document.write(i + "<br />"); } </script> </head> <body> </body> </html>
submitReset Code
ChapterCourseware