JavaScript for loop is used to repeatedly execute a piece of code. Its syntax is as follows:
##for (expr1; expr2; expr3){ statement
}
<!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
<!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.<!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>