こんにちは。
本日はJavaScriptのループ処理における
continue、breakについてのメモです。
概要
ループ処理で使用するforEachですが、
continue、breakが使用できないんですよね。
なので、ループ処理で上記を実現する方法について
調べてみたのでメモです。
for
一番シンプル。
forを使用すればcontinueもbreakも使用できます。
const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] for (let i = 0; i < arr.length; i++) { if (arr[i] === 'c') { continue } if (arr[i] === 'f') { break } console.log(arr[i]) }
出力結果は以下です。
a b d e
forEach
forEachで以下のようにcontinueやbreakを使用した場合
if (x === 'c') { continue }
if (x === 'f') { break }
以下のエラーが発生します。
- Uncaught SyntaxError: Illegal break statement
- Uncaught SyntaxError: Illegal continue statement: no surrounding iteration statement
forEachはメソッドなのでcontinueもbreakも使用できません...
なので、returnとすることでcontinueを実現してみます。
const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] arr.forEach(x => { if (x === 'c') { return } console.log(x) });
以下出力結果です。
a b d e f g
残るはbreakですが、そもそもforEachは中断することができる仕様になっていません。
なので、forEachを使用した場合は、breakのような動作は不可能となります。
some
someもメソッドの1つです。
このメソッドは、trueが返ってくるまで処理を続けます。
この性質を利用してcontinueとbreakを実現します。
const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] arr.some(x => { if (x === 'c') { return } if (x === 'f') { return true } console.log(x) })
出力結果は以下です。
a b d e
まとめ
- forはcontinueもbreakも使用可能
- forEachはcontinueと同等の動作はできるが、breakのような動作はできない
- someはcontinue、breakと同等の動作ができる
以上です。