while loop: As long as the condition is true, the loop body code will be executed repeatedly
while (conditional judgment)
{
If the condition is true, the loop body code will be executed
}
While loop structure description:
Before the loop starts, it must Initialize the variable (declare the variable and give the variable an initial value).
If the condition of while is true, the code ({ }) in the loop body will be executed repeatedly. If the condition is false, exit the loop.
In the loop body, there must be a "variable update" statement. In other words: the values of the variables in the two loops cannot be the same. If they are the same, it will cause an "infinite loop".
Let’s learn through examples:
Output all numbers between 1-10
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> var i = 1; while(i<=10){ document.write(i); i++ //变量更新,是为了避免出现“死循环” } </script> </head> <body> </body> </html>
Loop statement There must be three elements, one of which is indispensable:
Variable initialization
Conditional judgment
Variable update
Output all odd numbers between 1-100
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> //变量初始化 var i = 1; //条件判断 while(i<=100){ //如果是奇数,则输出 if(!(i%2==0)){ document.write(i+" "); } //变量更新 i++; } </script> </head> <body> </body> </html>