106
87

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] ループ途中で抜ける処理は for(in break) ではなく some を使おう♪

Last updated at Posted at 2015-03-10

for(in break) より Array.prototype.some のほうがモダンな気分になれます.

for(in break)

5 より大きかったら break で抜ける

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

for (var i=0,len=arr.length; i<len; ++i) {
    var value = arr[i];
    if (value > 5) {
        break;
    }
    console.log(value);
}

[runstant]

Array.prototype.some

5 より大きかったら true を返す.
するとそれ以降のループが止まるので forEach っぽく書けてかつ break っぽいことができます.

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

arr.some(function(value) {
    if (value > 5) {
        return true;
    }
    console.log(value);
});

[runstant]

106
87
12

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
106
87

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?