search
LoginSignup
92
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

[JavaScript] ループ途中で抜ける処理は for(in break) ではなく some を使おう♪

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]

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
What you can do with signing up
92
Help us understand the problem. What are the problem?