LoginSignup
2
3

More than 3 years have passed since last update.

JSでArray.forEach() をbreakしたくなったら代わりにfor ... of を使おう

Last updated at Posted at 2020-04-12

掲題通り。

forEachはbreakできない

[0,1,2,3].forEach((v, i) => {
  if(i === 2){
    return;
  }
  console.log(v)
})
// 0と 1 と 3, breakする手段なし
// ※forEachは言語仕様的には順序保証がない

for ... ofはいいぞ(ES6)

ES6以降ならfor ofを使いましょう。 thx @rdlabo

for(const v of [1,2,3]){
  if(v === 2){
    break;
  }
  console.log(v) // 1
}
// 1
// 順序保証がある、この方法ではindexが使えない
for(const [i, v] of [0,1,2,3].entries()){
  if(i == 2){ 
    break;
  }
  console.log(v)
}
// 0, 1
// Arr.entries() と使うとofでもindexとvalueが使える
// 順序保証もある。がentries()はちょっとパフォーマンスが悪いらしい。計測してないけど。

ES5なら Array.some() が代用できる

ES5ならsomeが代用品として使えるけど微妙にsomeの目的に沿わないかも。

[0,1,2,3].some((v, i) => {
  if(i === 2){
    return true;
  }
  console.log(v)
}
// 0, 1
// Arr.someは本来test関数なので目的からそれてる

arr.some(callback[, thisArg])

callbackの受け取る引数は、 element, index[optional], array[optional] の3つです。
someそのものの第二引数thisArgについては基本わすれてもいいかと。

参考にしました

2
3
2

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
2
3