while loop in JavaScript
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++ //變量更新,是為了避免出現(xiàn)“死循環(huán)” } </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){ //如果是奇數(shù),則輸出 if(!(i%2==0)){ document.write(i+" "); } //變量更新 i++; } </script> </head> <body> </body> </html>