Оператор do...while створює цикл, який виконує вказану інструкцію, доки перевірочна умова не буде оцінена як false. Умова оцінюється після виконання інструкції, в результаті вказана інструкція виконується принаймні один раз.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Синтаксис
do statement while (condition);
statement- Інструкція, яка виконується принаймні один раз, і виконується повторно кожен раз, коли умова оцінюється як true. Для виконання кількох інструкцій, використовуйте
блок({ ... }), щоб згрупувати ці інструкції.
condition- Вираз, який оцінюється після кожного проходу циклу. Якщо
conditionоцінюється як true,statementвиконується повторно. Колиconditionоцінюється як false, контроль переходить до наступної післяdo...whileінструкції.
Приклад
Використання do...while
У наступному прикладі цикл do...while виконується принаймні один раз, і продовжує виконуватись, доки i не перестане бути менше 5.
HTML-зміст
<div id="example"></div>
JavaScript-зміст
var result = '';
var i = 0;
do {
i += 1;
result += i + ' ';
} while (i > 0 && i < 5); // Хоча i == 0, цикл виконається, оскільки починається без перевірки
document.getElementById('example').innerHTML = result;
Результат
Специфікації
| Специфікація | Статус | Коментар |
|---|---|---|
| ECMAScript 3rd Edition (ECMA-262) | Standard | Початкове визначення. Реалізоване у JavaScript 1.2 |
| ECMAScript 5.1 (ECMA-262) The definition of 'do-while statement' in that specification. |
Standard | |
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'do-while statement' in that specification. |
Standard | Кінцева крапка з комою ; тепер необов'язкова. |
| ECMAScript Latest Draft (ECMA-262) The definition of 'do-while statement' in that specification. |
Draft |
Сумісність з веб-переглядачами
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
do...while | Chrome Full support Yes | Edge Full support Yes | Firefox Full support 1 | IE Full support 6 | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes | nodejs Full support Yes |
Legend
- Full support
- Full support

