Ask Ben: Iterating Over An Array With jQuery

Posted November 17, 2008 at 8:33 AM

Tags: Javascript / DHTML, Ask Ben

Hi; I'm new to jquery. I have php array like:

$arr = array("one", "two", "three");

I would like to convert this array ( or copy its values) to jquery array and use .each. can someone show me this .

There are two different "each" methods in jQuery. One of them works on the jQuery stack (of DOM elements) and one of them is a utility object. They very might well work off of each other behind the scenes, but from an API view, these are two different methods with two different purposes. Luckily, the $.each() jQuery utility method does exactly what you need it to.

In the following demo, we are gonna take a Javascript array and, without any need to convert it to a jQuery array, loop over its values and add them to the document object model (DOM):

 Launch code in new window » Download code as text file »

  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  • <html>
  • <head>
  • <title>Looping Over Arrays With jQuery</title>
  •  
  • <!-- Linked files. -->
  • <script type="text/javascript" src="jquery-1.2.6.min.js"></script>
  • <script type="text/javascript">
  •  
  • // Init the page once the DOM has loaded.
  • $( InitPage );
  •  
  •  
  • // Init the page.
  • function InitPage(){
  • // Get a refernce to the OL list element.
  • var jList = $( "#list" );
  •  
  • // Create our test array.
  • var arrValues = [ "one", "two", "three" ];
  •  
  • // Loop over each value in the array.
  • $.each(
  • arrValues,
  • function( intIndex, objValue ){
  •  
  • // Create a new LI HTML element out of the
  • // current value (in the iteration) and then
  • // add this value to the list.
  • jList.append(
  • $( "<li>" + objValue + "</li>" )
  • );
  • }
  • );
  •  
  • }
  •  
  • </script>
  • </head>
  • <body>
  •  
  • <h1>
  • Looping Over Arrays With jQuery
  • </h1>
  •  
  • <p>
  • Array Items:
  • </p>
  •  
  • <!---
  • This is the list into which we will be storing
  • the array items.
  • --->
  • <ol id="list">
  • <!--- List items will be added dynamically. --->
  • </ol>
  •  
  • </body>
  • </html>

Notice that the $.each() method takes two parameters - the current index of the array iteration and the value that was found in the array at that index. Once we have this value, we simply use jQuery to add it to the ordered list element on the page. Running the above code, our rendered page looks like this:

Array Items:

1. one
2. two
3. three

Now, looking at this code, it might seem that the $.each() method is actually more work than a standard FOR index-loop; and, at face value, it is. But, with this small bit of additional overhead, $.each() gives us a load of benefits. By passing each iteration value to a function, we create a new local scope in which to work, we create a Closure that has awesome potential, and we create a new variable for each loop value which removes many conflicts one can run into when binding event handlers.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Other Searches  |  Print Page


You Might Also Be Interested In:




Reader Comments

Nov 17, 2008 at 9:28 AM // reply »
225 Comments

Why is it that this line, $.each(, containts a pointer to your array? Ie, why isn't it: somevariable.each(


Nov 17, 2008 at 9:59 AM // reply »
7,457 Comments

@Ray,

I think that's how Prototype does it; but since jQuery doesn't alter the core javascript objects, there is no each() method in the javascript array class (at least not that I know of).


Nov 17, 2008 at 11:37 AM // reply »
225 Comments

I'm still confused though. How does the browser know that you are iterating over some variable? All you have is $. What if you had 2 arrays? Where is the 'link' - does that make sense? It would be like me doing

<cfoutput>#arrayLen()#</cfoutput>

withouth passing an array.


Nov 17, 2008 at 11:44 AM // reply »
7,457 Comments

@Ray,

I think I see what you're saying. The confusion, I think, comes from the fact that when you are dealing with the jQuery stack, you can call .each() directly on that stack:

jQueryVariable.each( fnCallback );

The $.each() utility method, on the other hand, does *not* know what variable it is acting on. That is why the $.each() method takes the target variable as its first argument:

$.each( AnyArrayVariable, fnCallback );

In either case, the "this" scope of the loop points to the current iteration value. In the former example, "this" points to the current DOM element; in the latter case, the "this" scope points to the array value (one, two, or three).

To be honest, I would not be surprised if the jQueryVariable.each() method actually turned around and called the utility method on its own internal stack.


Nov 17, 2008 at 4:14 PM // reply »
76 Comments

@Ben,

Exactly right. Also internally it $().each() does call $.each() to iterate the stack :)


Nov 17, 2008 at 5:24 PM // reply »
7,457 Comments

@Shuns,

Thanks for the clarification. I figured it would do as much just to cut down on code duplication.


Nov 17, 2008 at 9:55 PM // reply »
76 Comments

Yeah, thats sort of a key mantra with jQuery - as dry as possible


Nov 17, 2008 at 9:57 PM // reply »
7,457 Comments

@Shuns,

Word up, jQuery is rockin.


Nov 18, 2008 at 8:09 PM // reply »
44 Comments

@Ben,

Is this PHP user Ray? I want to know if he's doing PHP on the side instead of Coldfusion, lol!


Nov 19, 2008 at 8:11 AM // reply »
7,457 Comments

@Hatem,

Ha ha ha :) Php :)


Nov 24, 2009 at 1:46 AM // reply »
1 Comments

Thanks for this!


Nov 27, 2009 at 6:24 AM // reply »
1 Comments

@Ray,

I'm quite new to jQuery, but I think it's also possible to convert the array to a jQuery object and iterate it directly via each.

The jQuery intelligently handles different datatypes given as first param (selector) in init method (at least in version 1.3.2 I'm using) so these two examples should do the same thing.

// Give the array as parameter to jQuery.each
$.each(["one", "two", "three"], function(index) {
console.debug(index + ': ' + this);
});

// Give the array to $ and iterate the returned jQuery array object using its each method
$(["one", "two", "three"]).each(function(index) {
console.debug(index + ': ' + this);
});

Same amount of code though, no major difference here.


Jan 9, 2010 at 10:47 PM // reply »
7,457 Comments

@Perttu,

I am not 100% sure, but I think underneath, the $().each() method actually uses the $.each() method behind the scenes; so, to you're point, either way is good.


Jan 21, 2010 at 2:12 PM // reply »
1 Comments

Very simple implementation hash table.

//code
var Hash = function(){
var indexes = new Array();
var values = new Array();
//objHash.set('indexName', 123)
this.set = function(name,value){
var locationIndex = indexes.indexOf(name);
if(locationIndex==-1){
locationIndex = indexes.length;
indexes[locationIndex] = name;
}
values[locationIndex] = value;
}
//objHash.get('indexName')
this.get = function(name){
return values[indexes.indexOf(name)];
}

//objHash.each(function(index,value))
this.each = function(callback){
document.write(indexes.length)
for(var i=0;i<indexes.length;i++){
callback(indexes[i], values[i]);
}
}
}

//Example usage:

var names = new Hash();
names.set('steven','name@email.com');
document.write("Find " + names.get('steven') + "<br />");

names.each(function(index,value){
document.write("<li>" + index + " - "+value+"</li>");


Jan 21, 2010 at 8:58 PM // reply »
7,457 Comments

@Steven,

That's a cool idea - thanks for sharing.


Feb 18, 2010 at 4:48 PM // reply »
1 Comments

Thanks:) Your blog rocks I read it everyday and syndicate it with twitter @seacloud9! Your tips save me time I owe you one:)


Feb 22, 2010 at 9:11 PM // reply »
7,457 Comments

@Brendon,

Oh wow, that's awesome! Thanks. I'll check out your Twitter aggregation.


Post Comment  |  Ask Ben

Recent Blog Comments
Tim
Mar 9, 2010 at 11:21 PM
DreamWeaver CS3 Slows Me Down
Revisiting the slow upload probs. On Vista & DW CS3 I had long waits when uploading locally and to a SFTP server. "Maintain synchronization information" within the site definition was the problem. Un ... read »
Mar 9, 2010 at 6:57 PM
Terms Of Service / Privacy Policy Document Generator
Thanks so much!!!! Definitely going to refer this to others. ------- Yanike Mann http://www.yeoworks.com ... read »
Mar 9, 2010 at 5:03 PM
Ask Ben: Javascript Replace And Multiple Lines / Line Breaks
Hello Ben, I'm having a lot of problems with a function that transform an single-line input-given value in a slug. The function is: function slug(fromm, tooo) { if (document.getElementById(fromm)) { ... read »
Mar 9, 2010 at 4:47 PM
ColdFusion, jQuery, And "AJAX" File Upload Demo
Oh, for crying out loud! Never mind, I figured it out! (slapping myself up side the head). It's been a really long day. Ok, so this works perfectly. Thank you for the great code! And for letti ... read »
Mar 9, 2010 at 4:38 PM
ColdFusion, jQuery, And "AJAX" File Upload Demo
I'm having a bugger of a time with this. I'm trying to use it with PHP instead. I know the PHP script works fine without the javascript (just submitting a regular form) and according to FireBug, th ... read »
Mar 9, 2010 at 4:25 PM
Calculating Your Weight Lifting Rep Maximum Using ColdFusion
The reason for the percentages being different work intensities for shoulders vs bench press is that there is further formulas required which integrate co-efficients relative to muscle mechanics for ... read »
Mar 9, 2010 at 4:01 PM
Ask Ben: Reading In A File Using CFFile And CFInclude
Ben, do you know what is the size of the file CFFILE can read into one variable. I have a big text file which is 350 K with over 250 K records. It seems that ColdFusion refuse to read the file into ... read »
Mar 9, 2010 at 3:36 PM
Ask Ben: Getting The Start And End Dates Of The Previous Week In ColdFusion
Is this example providing the previous week or is it providing a span of 7 days which may include last week? ... read »