How to loop through array in jQuery?

Viewed 875981

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?

12 Answers

ES6 syntax with arrow function and interpolation:

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

Try this:

$.grep(array, function(element) {

})

$.map(data,function(elem) {...})

$.map(data,function(elem){
   console.log(elem);
})
            
   

Alternative ways of iteration through array/string with side effects

var str = '21,32,234,223';
var substr = str.split(',');

substr.reduce((a,x)=> console.log('reduce',x), 0)        // return undefined

substr.every(x=> { console.log('every',x); return true}) // return true

substr.some(x=> { console.log('some',x); return false})  // return false

substr.map(x=> console.log('map',x));                    // return array
 
str.replace(/(\d+)/g, x=> console.log('replace',x))      // return string

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

} 
Related