Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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