How to loop through array in jQuery?

844,144

Solution 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));

...or Function#bind:

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

...or in ES2015 ("ES6"), an arrow function:

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

What NOT to do:

Don't use for..in for this (or if you do, do it with proper safeguards). You'll see people saying to (in fact, briefly there was an answer here saying that), but for..in does not do what many people think it does (it does something even more useful!). Specifically, for..in loops through the enumerable property names of an object (not the indexes of an array). Since arrays are objects, and their only enumerable properties by default are the indexes, it mostly seems to sort of work in a bland deployment. But it's not a safe assumption that you can just use it for that. Here's an exploration: http://jsbin.com/exohi/3

I should soften the "don't" above. If you're dealing with sparse arrays (e.g., the array has 15 elements in total but their indexes are strewn across the range 0 to 150,000 for some reason, and so the length is 150,001), and if you use appropriate safeguards like hasOwnProperty and checking the property name is really numeric (see link above), for..in can be a perfectly reasonable way to avoid lots of unnecessary loops, since only the populated indexes will be enumerated.

Solution 2

jQuery.each()

jQuery.each()

jQuery.each(array, callback)

array iteration

jQuery.each(array, function(Integer index, Object value){});

object iteration

jQuery.each(object, function(string propertyName, object propertyValue){});

example:

var substr = [1, 2, 3, 4];
$.each(substr , function(index, val) { 
  console.log(index, val)
});

var myObj = { firstName: "skyfoot"};
$.each(myObj, function(propName, propVal) {
  console.log(propName, propVal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

javascript loops for array

for loop

for (initialExpression; condition; incrementExpression)
  statement

example

var substr = [1, 2, 3, 4];

//loop from 0 index to max index
for(var i = 0; i < substr.length; i++) {
  console.log("loop", substr[i])
}

//reverse loop
for(var i = substr.length-1; i >= 0; i--) {
  console.log("reverse", substr[i])
}

//step loop
for(var i = 0; i < substr.length; i+=2) {
  console.log("step", substr[i])
}

for in

//dont really wnt to use this on arrays, use it on objects
for(var i in substr) {
    console.log(substr[i]) //note i returns index
}

for of

for(var i of subs) {
    //can use break;
    console.log(i); //note i returns value
}

forEach

substr.forEach(function(v, i, a){
    //cannot use break;
    console.log(v, i, a);
})

Resources

MDN loops and iterators

Solution 3

No need for jquery here, just a for loop works:

var substr = currnt_image_list.split(',');
for(var i=0; i< substr.length; i++) {
  alert(substr[i]);
}

Solution 4

Option 1 : The traditional for-loop

The basics

A traditional for-loop has three components :

  1. the initialization : executed before the look block is executed the first time
  2. the condition : checks a condition every time before the loop block is executed, and quits the loop if false
  3. the afterthought : performed every time after the loop block is executed

These three components are seperated from each other by a ; symbol. Content for each of these three components is optional, which means that the following is the most minimal for-loop possible :

for (;;) {
    // Do stuff
}

Of course, you will need to include an if(condition === true) { break; } or an if(condition === true) { return; } somewhere inside that for-loop to get it to stop running.

Usually, though, the initialization is used to declare an index, the condition is used to compare that index with a minimum or maximum value, and the afterthought is used to increment the index :

for (var i = 0, length = 10; i < length; i++) {
    console.log(i);
}

Using a tradtional for-loop to loop through an array

The traditional way to loop through an array, is this :

for (var i = 0, length = myArray.length; i < length; i++) {
    console.log(myArray[i]);
}

Or, if you prefer to loop backwards, you do this :

for (var i = myArray.length - 1; i > -1; i--) {
    console.log(myArray[i]);
}

There are, however, many variations possible, like eg. this one :

for (var key = 0, value = myArray[key], var length = myArray.length; key < length; value = myArray[++key]) {
    console.log(value);
}

... or this one ...

var i = 0, length = myArray.length;
for (; i < length;) {
    console.log(myArray[i]);
    i++;
}

... or this one :

var key = 0, value;
for (; value = myArray[key++];){ 
    console.log(value);
}

Whichever works best is largely a matter of both personal taste and the specific use case you're implementing.

Note :

Each of these variations is supported by all browsers, including véry old ones!


Option 2 : The while-loop

One alternative to a for-loop is a while-loop. To loop through an array, you could do this :

var key = 0;
while(value = myArray[key++]){
    console.log(value);
}
Note :

Like traditional for-loops, while-loops are supported by even the oldest of browsers.

Also, every while loop can be rewritten as a for-loop. For example, the while-loop hereabove behaves the exact same way as this for-loop :

for(var key = 0;value = myArray[key++];){
    console.log(value);
}

Option 3 : for...in and for...of

In JavaScript, you can also do this :

for (i in myArray) {
    console.log(myArray[i]);
}

This should be used with care, however, as it doesn't behave the same as a traditonal for-loop in all cases, and there are potential side-effects that need to be considered. See Why is using "for...in" with array iteration a bad idea? for more details.

As an alternative to for...in, there's now also for for...of. The following example shows the difference between a for...of loop and a for...in loop :

var myArray = [3, 5, 7];
myArray.foo = "hello";

for (var i in myArray) {
  console.log(i); // logs 0, 1, 2, "foo"
}

for (var i of myArray) {
  console.log(i); // logs 3, 5, 7
}
Note :

You also need to consider that no version of Internet Explorer supports for...of (Edge 12+ does) and that for...in requires at least IE10.


Option 4 : Array.prototype.forEach()

An alternative to For-loops is Array.prototype.forEach(), which uses the following syntax :

myArray.forEach(function(value, key, myArray) {
    console.log(value);
});
Note :

Array.prototype.forEach() is supported by all modern browsers, as well as IE9+.


Option 5 : jQuery.each()

Additionally to the four other options mentioned, jQuery also had its own foreach variation.

It uses the following syntax :

$.each(myArray, function(key, value) {
    console.log(value);
});

Solution 5

Use the each() function of jQuery.

Here is an example:

$.each(currnt_image_list.split(','), function(index, value) { 
  alert(index + ': ' + value); 
});
Share:
844,144

Related videos on Youtube

Rickstar
Author by

Rickstar

Updated on October 14, 2021

Comments

  • Rickstar
    Rickstar over 2 years

    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?

  • jAndy
    jAndy over 13 years
    using .each() or for...in to loop over an array is in general a bad idea. It's just like ages slower than using for or while. Using a for loop it's even a great idea to cache the length property before looping. for (var i = 0, len = substr.length; i < len; ...
  • T.J. Crowder
    T.J. Crowder over 13 years
    @jAndy: I believe I did mention speed being an advantage of the first one. Re caching the length, it would have to be a REALLY big array to be worth the overhead, but fair 'nuff.
  • Mike Purcell
    Mike Purcell almost 8 years
    The disadvantage for jquery could be removed if you use $.proxy
  • T.J. Crowder
    T.J. Crowder almost 8 years
    @MikePurcell: Or an arrow function. Or Function#bind. :-) Good point, added.
  • user889030
    user889030 over 7 years
    hmmmm ++i or i++
  • Lord Nighton
    Lord Nighton about 7 years
    Very nice solution!
  • Doug S
    Doug S over 6 years
    Correct me if I'm wrong but shouldn't your Generic loop example be i++ instead of ++i? Otherwise, you're skipping the first item.
  • T.J. Crowder
    T.J. Crowder over 6 years
    @DougS: No, the only difference between i++ and ++i is the result of that expression, which is never used in the example above. A for loop works like this: 1. Initialization, 2. Test (terminate if false), 3. Body, 4. Update, 5. Return to Step 2. The result of the update expression isn't used for anything.
  • Admin
    Admin about 6 years
    just a quick word if caution - most likely none of the above script examples will work in IE. It would appear that MS in their infinite wisdom, made word "item" a reserved word in IE, so you can't use it as an variable.
  • T.J. Crowder
    T.J. Crowder about 6 years
    @user3818264: No, item is not a reserved word on IE. You can use item as an identifier just fine on IE, and I have, repeatedly, for years. Proof (will run on any version of IE from IE6 onward if JSBin works on IE6 or IE7; will definitely work on IE8+ as I know JSBin works on those): output.jsbin.com/fipemagilu
  • Admin
    Admin about 6 years
    @T.J.Crowder - somehow not too long time ago I spend half a day throwing profanities as my code would not work on IE. All i was doing was item={i build and object here};my_array.push[item]; There was no other place the word "item" was used on the entire page, I check like 6 time. Once I changed "item" to "i" the page started working on IE. And I found this in one of the comments somehwere here on SO
  • T.J. Crowder
    T.J. Crowder about 6 years
    @user3818264: You were probably trying to use it as a global without a declaration, like this: output.jsbin.com/nefiziyoko item is a global function on IE that you can't overwrite. But that has no effect on your ability to use item as an identifer (variable or parameter), you just have to declare it: output.jsbin.com/gabuwozoxa
  • T.J. Crowder
    T.J. Crowder over 5 years
    @Crashalot - forEach is supported by everything you're likely to run into. (It isn't supported by IE8, and sadly can't be properly polyfilled on IE8.)
  • d_kennetz
    d_kennetz about 5 years
    Hi! Please add some explanation as to how this solves OP's problem. It is generally discouraged on SO to post code only answers as they do not help OP or future visitors understand the answer. Thanks! --From Review.
  • General Grievance
    General Grievance almost 4 years
  • Nico Haase
    Nico Haase almost 4 years
    Please add some explanation to your answer such that others can learn from it - especially as this is a very old question that already holds some answers