3

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?

1
  • don't loop over an array with for..in or .each()! Commented Jul 25, 2010 at 17:10

5 Answers 5

2

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.
});
Sign up to request clarification or add additional context in comments.

1 Comment

@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) {...});
0

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.

Comments

0

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

Comments

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

Comments

0

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++){
}

3 Comments

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: that comment does not make sense to my post? :p
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()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.