The Wayback Machine - https://web.archive.org/web/20160413100850/https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/while

Account creation on MDN is disabled while we upgrade our moderation mechanisms. If you see something that needs to be fixed, please file a bug: https://bugzilla.mozilla.org/form.doc and we'll handle it as soon as we can. Thanks for your patience!

テスト条件が true に評価される間、指定された文を実行するループを作成します。条件は文を実行する前に評価されます。

構文

while (condition) {
  statement
}

condition

ループを通過する前ごとに評価される式。もしこの条件が true に評価されるなら、statement が実行されます。条件が false に評価されるときは、while ループの後の文に実行が続きます。
statement
条件が true に評価される間実行される文。ループ内で複数の文を実行するには、それらの文をグループ化するためにブロック文 ({ ... }) を使ってください。

次の while ループは、n が 3 より小さい間反復します。

var n = 0;
var x = 0;
while (n < 3) {
  n ++;
  x += n;
}

それぞれの反復で、ループは n を増加させ、それを x に足します。ゆえに、x および n は次の値をとります:

  • 最初の通過の後: n = 1 かつ x = 1
  • 2 回目の通過の後: n = 2 かつ x = 3
  • 3 回目の通過の後: n = 3 かつ x = 6

3 回目の通過が完了した後、条件 n < 3 はもはや true ではなく、ループは終了します。

参照

do...while, for

ドキュメントのタグと貢献者

 このページの貢献者: teoli, ethertank, Mgjbot, Nanto vi
 最終更新者: teoli,
HTTPS · web.archive.org
← Home