views:

72

answers:

5

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() {
                loop through the array
                            var rndTile = the current array digit

                $(this).css({ 'background-image': 'url(images/'+arrayDigit+'.jpg' });
            });

How could I implement this?

+2  A: 

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.
});
g.d.d.c
Groovy, cheers v. much!
Neurofluxation
@Neurofluxation - If you're going to use `.each()` to iterate over your array, you don't need to create a jQuery object. Just do `$.each(gridArray, function(i,val) {...});`
patrick dw
A: 

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.

echo
A: 

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' });
});
Tomalak
A: 
$('li.node').each(function(index) {
    var rndTile = gridArray[index % gridArray.length];
    $(this).css({ 'background-image': 'url(images/' + rndTile + '.jpg' });
});
Darin Dimitrov
A: 

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++){
}
jAndy
Not to discourage (or disparage) all of the avid web developers out there but please, *please*, learn JavaScript *before* you learn a library! (ie. jQuery, MooTools, Dojo, or Prototype) It'll make you a better developer and your code'll be faster/better!
indieinvader
@indieinvader: that comment does not make sense to my post? :p
jAndy
I guess it was a little out of context, what I was trying to say is that this should be obvious. But because most new JS developers don't learn the language, they learn jQuery, et al they end up inadvertently writing bad code or worse, confused when they find out that jQuery !== JavaScript!tl;dr: you're right, `for` is better than `.each()`
indieinvader