0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScript勉強の記録その5: breakとcontinueを使ったループ処理

Posted at

breakとcontinueを使ったループ処理

breakやcontinueを利用して、ある条件の時にはループ処理を抜けたり、次のループ処理に入ったり等、制御をすることができます。 
まず、以下の例では変数が3の倍数の時にコンソールに「こんにちは」と表示します。

index.js
for (let i = 1; i <= 10 ; i++) {
  if (i % 3 === 0) {
    console.log('こんにちは');
  }
  console.log(i);
}

// 1
// 2
// こんにちは
// 3
// 4
// 5
// こんにちは
// 6
// 7
// 8
// こんにちは
// 9
// 10

上記の例では3の倍数の時には、「こんにちは」と「3の倍数」が出力されてありますが、「3の倍数」の時は、数字は表示せず、「こんにちは」だけ表示したいときもあるかと思います。
そのような時は、continueという命令を加えることで、制御を加えることができます。

以下の例ではcontinueが呼ばれた時点で次のループ処理に入ることができますので一番下のconsole.log(i)は呼ばれません。

index.js
for (let i = 1; i <= 10 ; i++) {
  if (i % 3 === 0) {
    console.log('こんにちは');
    continue;
  }
  console.log(i);
}

// 1
// 2
// こんにちは
// 4
// 5
// こんにちは
// 7
// 8
// こんにちは
// 10

最後に、ある条件に当てはまった時点でループ処理を抜けたい、という時もあるかと思います。
そう言う時はbreakという命令を使えば、その時点でループ処理を抜けられます。

index.js
for (let i = 1; i <= 10 ; i++) {
  if (i % 3 === 0) {
    console.log('こんにちは');
    break;
  }
  console.log(i);
}

// 1
// 2
// こんにちは
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?