Exploring JavaScript: Iterating Over a Collection of Items

If I manage to do it, I'd like to write a series of introductory posts about programming in JavaScript as when listening to the latest hypes it is going to play a major role in programming the web but even desktop or mobile apps (see Microsoft's latest moves regarding Silverlight, HTML5 and their new Win8 OS). Google has always been an early promoter of heavy, rich-client JavaScript applications and as a recent example I'd also like to mention Trello, a quite new app from Fog Creek, which I started to use for organizing my work/projects and which is a JavaScript app that will blow you away ;).

So here the first post in the series "exploring JavaScript" (I'll also tag them as such so you can easily keep track). Please do not pay attention at the order of how posts arrive related to the concepts in JavaScript. So I might write now about iterating over collections and at a later point about potential problems in using variable declarations, scoping or data types :). I'll write them as I encounter those problems.

So this post outlines some possibilities of iterating over collections of items. Using the standard for-loop
Similarly as in other language, there is the normal for-loop.
var list = ["entry1", "entry2", "entry3"];
for(var i=0; i<list.length; i++){
$("#out").append($("<div>" + i + " - " + list[i] + "</div>"));
}

Using the "foreach"
Note, the foreach loop iterates over the properties of a given object which might be slightly different than in other programming languages such as C# or Java.
var list = ["entry1", "entry2", "entry3"];
for(var entry in list){
$("#out").append($("<div>" + entry + " - " + list[entry] + "</div>"));
}
The usage of the for-in loop for arrays is highly discouraged, however. See this Stackoverflow post:
http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays

Using jQuery.each(...)
Beside the normal JavaScript build-in functions, one can also use the jQuery.each which does not only allow to iterate over a collection of DOM elements captured by the specified selector, but also through JavaScript collections.
var list = ["entry1", "entry2", "entry3"];
$.each(list, function(index, value){
$("#out").append($("<div>" + index + " - " + value + "</div>"));
});
...or alternatively like...
var list = ["entry1", "entry2", "entry3"];
$(list).each(function(index, value){
$("#out").append($("<div>" + index + " - " + value + "</div>"));
});
Kindle

Comments

0

Your ad here?