Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
91
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

[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]

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
91
Help us understand the problem. What are the problem?