[javascript] How to loop through array in jQuery?

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?

This question is related to javascript jquery arrays loops iteration

The answer is


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]);
}

ES6 syntax with arrow function and interpolation:

var data=["a","b","c"];
$(data).each((index, element) => {
        console.log(`current index : ${index} element : ${element}`)
    });

  for(var key in substr)
{
     // do something with substr[key];

} 

Try this:

$.grep(array, function(element) {

})

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:

_x000D_
_x000D_
var substr = [1, 2, 3, 4];_x000D_
$.each(substr , function(index, val) { _x000D_
  console.log(index, val)_x000D_
});_x000D_
_x000D_
var myObj = { firstName: "skyfoot"};_x000D_
$.each(myObj, function(propName, propVal) {_x000D_
  console.log(propName, propVal);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

javascript loops for array

for loop

for (initialExpression; condition; incrementExpression)
  statement

example

_x000D_
_x000D_
var substr = [1, 2, 3, 4];_x000D_
_x000D_
//loop from 0 index to max index_x000D_
for(var i = 0; i < substr.length; i++) {_x000D_
  console.log("loop", substr[i])_x000D_
}_x000D_
_x000D_
//reverse loop_x000D_
for(var i = substr.length-1; i >= 0; i--) {_x000D_
  console.log("reverse", substr[i])_x000D_
}_x000D_
_x000D_
//step loop_x000D_
for(var i = 0; i < substr.length; i+=2) {_x000D_
  console.log("step", substr[i])_x000D_
}
_x000D_
_x000D_
_x000D_

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


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

You can use a for() loop:

var things = currnt_image_list.split(','); 
for(var i = 0; i < things.length; i++) {
    //Do things with things[i]
}

Use jQuery each(). There are other ways but each is designed for this purpose.

$.each(substr, function(index, value) { 
  alert(value); 
});

And do not put the comma after the last number.


Alternative ways of iteration through array/string with side effects

_x000D_
_x000D_
var str = '21,32,234,223';_x000D_
var substr = str.split(',');_x000D_
_x000D_
substr.reduce((a,x)=> console.log('reduce',x), 0)        // return undefined_x000D_
_x000D_
substr.every(x=> { console.log('every',x); return true}) // return true_x000D_
_x000D_
substr.some(x=> { console.log('some',x); return false})  // return false_x000D_
_x000D_
substr.map(x=> console.log('map',x));                    // return array_x000D_
 _x000D_
str.replace(/(\d+)/g, x=> console.log('replace',x))      // return string
_x000D_
_x000D_
_x000D_


Use the each() function of jQuery.

Here is an example:

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to iteration

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? How to loop over grouped Pandas dataframe? How to iterate through a list of dictionaries in Jinja template? How to iterate through an ArrayList of Objects of ArrayList of Objects? Ways to iterate over a list in Java Python list iterator behavior and next(iterator) How to loop through an array containing objects and access their properties recursion versus iteration What is the perfect counterpart in Python for "while not EOF" How to iterate over a JavaScript object?