JavaScript do/whileStatement

JavaScript 语句参考手册JavaScript Statement Reference

Examples

The loop will always be executed at least once, even if the condition is false, because the code block is executed before the conditional statement is tested:

var text = "" var i = 0; do { text += "<br>The number is" + i; i++; } while (i < 5); document.getElementById("demo").innerHTML = text;

textThe output result is:

数字为 0
数字为 1
数字为 2
数字为 3
数字为 4

Try it yourself »


Definition and Usage

The do/while loop is a variant of the while loop. This loop will execute a code block once, before checking whether the condition is true, and then it will repeat this loop if the condition is true.

JavaScript supports different types of loops:

  • for - A loop can execute a code block a specified number of times.
  • for/in - Loop through the properties of an object.
  • while - Loop a specified code block while the specified condition is true.
  • do/while- Also loop a specified code block while the specified condition is true, but this loop executes the code block once before testing the condition.

Browser Support

Statement
do/while Yes Yes Yes Yes Yes


Syntax

do {
    执行代码
} while (condition);

Parameter Values

Parameter Description
condition Required. Defines the condition for executing the loop. If it returns true, the loop will execute again; if it returns false, the loop ends.

Note:If the condition is always true, the loop will never end (infinite loop). This will cause your browser to crash.

Note:If you use a variable as the condition, initialize the variable before the loop starts and increment it inside the loop. If you forget to increment the variable, an infinite loop will occur, and the browser will also crash.

Technical Details

JavaScript version: 1.2


Related Pages

JavaScript Tutorial:JavaScript While Loop

JavaScript Reference:JavaScript while Statement

JavaScript Reference:JavaScript for Statement


JavaScript 语句参考手册JavaScript Statement Reference Other Extensions