Оператор 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 (ECMA-262) The definition of 'do-while statement' in that specification. |
Living Standard |
Сумісність з веб-переглядачами
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 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 4 | Opera Full support 4 | Safari Full support 1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support 0.1.100 |
Legend
- Full support
- Full support