How to loop through array in jQuery? Ask Question

How to loop through array in jQuery? Ask Question

I am trying to loop through an array. I have the following code:

 var currnt_image_list= '21,32,234,223';
 var substr = currnt_image_list.split(','); // array here

Am trying to get all the data out of the array. Can some one lead me in the right path please?

ベストアンサー1


(Update: My other answer here lays out the non-jQuery options much more thoroughly. The third option below, jQuery.each, isn't in it though.)


Four options:

Generic loop:

var i;
for (i = 0; i < substr.length; ++i) {
    // do something with `substr[i]`
}

or in ES2015+:

for (let i = 0; i < substr.length; ++i) {
    // do something with `substr[i]`
}

Advantages: Straight-forward, no dependency on jQuery, easy to understand, no issues with preserving the meaning of this within the body of the loop, no unnecessary overhead of function calls (e.g., in theory faster, though in fact you'd have to have so many elements that the odds are you'd have other problems; details).

ES5's forEach:

As of ECMAScript5, arrays have a forEach function on them which makes it easy to loop through the array:

substr.forEach(function(item) {
    // do something with `item`
});

Link to docs

(Note: There are lots of other functions, not just forEach; see the answer referenced above for details.)

Advantages: Declarative, can use a prebuilt function for the iterator if you have one handy, if your loop body is complex the scoping of a function call is sometimes useful, no need for an i variable in your containing scope.

Disadvantages: If you're using this in the containing code and you want to use this within your forEach callback, you have to either A) Stick it in a variable so you can use it within the function, B) Pass it as a second argument to forEach so forEach sets it as this during the callback, or C) Use an ES2015+ arrow function, which closes over this. If you don't do one of those things, in the callback this will be undefined (in strict mode) or the global object (window) in loose mode. There used to be a second disadvantage that forEach wasn't universally supported, but here in 2018, the only browser you're going to run into that doesn't have forEach is IE8 (and it can't be properly polyfilled there, either).

ES2015+'s for-of:

for (const s of substr) { // Or `let` if you want to modify it in the loop body
    // do something with `s`
}

See the answer linked at the top of this answer for details on how that works.

Advantages: Simple, straightforward, offers a contained-scope variable (or constant, in the above) for the entry from the array.

Disadvantages: Not supported in any version of IE.

jQuery.each:

jQuery.each(substr, function(index, item) {
    // do something with `item` (or `this` is also `item` if you like)
});

(Link to docs)

Advantages: All of the same advantages as forEach, plus you know it's there since you're using jQuery.

Disadvantages: If you're using this in the containing code, you have to stick it in a variable so you can use it within the function, since this means something else within the function.

You can avoid the this thing though, by either using $.proxy:

jQuery.each(substr, $.proxy(function(index, item) {
    // do something with `item` (`this` is the same as it was outside)
}, this));

...またはFunction#bind

jQuery.each(substr, function(index, item) {
    // do something with `item` (`this` is the same as it was outside)
}.bind(this));

...または ES2015 ("ES6") では、矢印関数:

jQuery.each(substr, (index, item) => {
    // do something with `item` (`this` is the same as it was outside)
});

してはいけないこと:

これに を使用しないでくださいfor..in(使用する場合は、適切な安全策を講じて行ってください)。 使用すべきだという意見を目にするでしょう (実際、ここで簡単にそのように回答していました) が、for..in多くの人が考えているようなことは行いません (もっと便利なことを行います!)。具体的には、for..inオブジェクトの列挙可能なプロパティ名 (配列のインデックスではありません) をループします。配列はオブジェクトであり、デフォルトでは列挙可能なプロパティはインデックスのみであるため、ほとんどは単調な展開でうまく機能するようです。しかし、そのためにこれを使用できると想定するのは安全ではありません。以下は調査です。http://jsbin.com/exohi/3

上記の「してはいけないこと」を和らげる必要があります。スパース配列 (たとえば、配列には合計 15 個の要素がありますが、そのインデックスが何らかの理由で 0 から 150,000 の範囲に散らばっているため、 はlength150,001 になります) を扱っている場合、およびhasOwnPropertyプロパティ名が実際に数値であることを確認する (上記のリンクを参照)などの適切な安全策を使用すると、for..in設定されたインデックスのみが列挙されるため、多数の不要なループを回避するのに完全に合理的な方法になります。

おすすめ記事