In JavaScript, while is a type of loop statement. The loop condition needs to be judged first. When the condition is satisfied, the loop body is executed. If it is not satisfied, the loop is jumped out. The characteristics of the while statement: first judge the expression, and execute the corresponding statement when the expression result is true.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
The while loop statement is awhen type
loop statement. The loop condition is first judged. When the condition is satisfied, the loop body is executed. If it is not satisfied, it stops.
Function:Repeat an operation until the specified condition is not true.
Features:Judge the expression first, and execute the corresponding statement when the expression result is true.
The general form of while loop is:
while(表达式){ //表达式为循环条件 语句块; //要执行的代码块 }
Statement analysis:
First calculate the value of "expression", When the value is true, the "statement block" in the loop body is executed;
Note: The calculation result of "expression" is of Boolean type (TRUE or FALSE). If it is a value of other types, it will also It will be automatically converted into a Boolean value (because PHP is a weak language type and will automatically convert the variable into the correct data type based on the value of the variable).
"Statement block" is a collection of one or more statements surrounded by {}; if there is only one statement in the statement block, {} can also be omitted.
After the execution is completed, return to the expression and calculate the value of the expression again for judgment. When the expression value is true, continue to execute the "statement block" ...This process will be repeated
until the value of the expression is false before jumping out of the loop and executing the statement below while.
The execution flow of the while loop is shown in the figure below:
Example: Use the while loop to calculate all integers between 1 and 100 The sum:
var i=1; var sum=0; while (i <= 100){ sum += i; i++; } document.write("1 + 2 + 3 + ... + 98 + 99 + 100 = " + sum)
Note:
When writing a loop statement, be sure to ensure that the result of the conditional expression can be false (i.e. Boolean value false), because as long as the result of the expression is true, the loop will continue and will not stop automatically. For this kind of loop that cannot stop automatically, we usually call it "infinite loop" or "infinite loop" ".
If you accidentally create an infinite loop, it may cause the browser or computer to freeze.
[Recommended learning:javascript advanced tutorial]
The above is the detailed content of What type of loop is javascript while. For more information, please follow other related articles on the PHP Chinese website!