Exploring JavaScript: Iterating Over a Collection of Items
2 min read
2 min read
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.var list = ["entry1", "entry2", "entry3"];
for(var i=0; i<list.length; i++){
$("#out").append($("<div>" + i + " - " + list[i] + "</div>"));
}
var list = ["entry1", "entry2", "entry3"];The usage of the for-in loop for arrays is highly discouraged, however. See this Stackoverflow post:
for(var entry in list){
$("#out").append($("<div>" + entry + " - " + list[entry] + "</div>"));
}
var list = ["entry1", "entry2", "entry3"];...or alternatively like...
$.each(list, function(index, value){
$("#out").append($("<div>" + index + " - " + value + "</div>"));
});
var list = ["entry1", "entry2", "entry3"];
$(list).each(function(index, value){
$("#out").append($("<div>" + index + " - " + value + "</div>"));
});