Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript do/while Statement

JavaScript do/while Statement

JavaScript Statement Reference JavaScript statement reference manual

Example

The loop executes at least once, even if the condition is false, because the code block runs before the condition is evaluated:

var

text

=

"

"

var

i

=

0

;

do

{

text

+=

"


The number is

"

i

;

i

++;

}

while

(

i

<

5

)

;

document

.

getElementById

(

"

demo

"

)

.

innerHTML

=

text

;

text The output result is:



数字为 0

数字为 1

数字为 2

数字为 3

数字为 4

Try it »


Definition and Usage

The do/while loop is a variant of the while loop. The loop executes the code block once before checking whether the condition is true, and then repeats the loop if the condition is true.

JavaScript supports different types of loops:


Browser support

Statement
do/while Yes Yes Yes Yes Yes

Syntax

do {

    执行代码

} while (condition);

Parameter value

Parameters Description
condition Required. Defines the condition for executing the loop. If it returns true, the loop runs again; if it returns false, the loop ends.
 **注意:** 如果条件一直为 true,循环将不会结束(无限循环)。这将会使你的浏览器崩溃。       

   

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

Technical Details

JavaScript version: 1.2

Related pages

JavaScript tutorial: JavaScript While Loop

JavaScript Reference Manual: JavaScript while Statement

JavaScript Reference Manual: JavaScript for Statement


JavaScript Statement Reference JavaScript statement reference manual