Skip to content Skip to sidebar Skip to footer

Jquery Question About Looping Through An Array

I have an array like this: var gridArray = [ 1,2,0,1,2,3,2,1,2,3,4,4,3,2,2,2,0 ] And I would like a jQuery each() function like this: $('li.node').each(function() {

Solution 1:

You need to pass parameters to your each callback.

$(gridArray).each(function (i, val) {
  // i is the index in this loop.// val is the value at gridArray[i] in this loop.
});

Solution 2:

Have a look at the jQuery Documentation for jQuery.each. The function signature is:

jQuery.each( collection, callback(indexInArray, valueOfElement) )

I'm not 100% sure what you're trying to accomplish, so it's hard to give a concrete example, but this should get you going.

Solution 3:

Assuming every array member correspondends to an <li>:

$('li.node').each(function(i) {
  var rndTile = gridArray[i];
  $(this).css({ 'background-image': 'url(images/'+rndTile+'.jpg' });
});

Solution 4:

$('li.node').each(function(index) {
    var rndTile = gridArray[index % gridArray.length];
    $(this).css({ 'background-image': 'url(images/' + rndTile + '.jpg' });
});

Solution 5:

It is in general a bad idea to loop over an array with for in or even worse, jQuerys .each(). Looping like that means lots of unnecesarry overhead.

Only use for..in or .each() if you don't know how many items you have to deal with (that in turn actually means only use it for objects).

Use a normal for loop to iterate over an array.

for(var n = 0, len = gridArray.length; n < len; n++){
}

Post a Comment for "Jquery Question About Looping Through An Array"