Create “foreach” functionality in JavaScript using an Array prototype function
In Javascript, there is no “foreach” statement. The closest thing we have is “for” syntax that will loop through all of the keys in a JavaScript object. Using the “for” syntax, we can access property values from the object, such as:
var myArray = [];
myArray.push("First Item");
myArray.push("Second Item");
myArray.push("Third Item");
myArray.customProperty = "Hello";
for (var item in myArray)
window.alert(myArray[item]);
While this syntax is great for reflecting, it is not the desired result for a “foreach” statement. The reason is, the code above will return not only the items that were pushed onto the array, but also the custom property and any other properties that we were attached (including functions!).
I have written a simple Array prototype function to supply “foreach” functionality:
Array.prototype.each = function(callback) {
var args = [null];
for (var index = 0; index != this.length; index++) {
args[0] = index;
callback.apply(this[index], args);
}
};
Once I have my prototype function in place, I can write code like the follow:
var myArray = [];
myArray.push("First Item");
myArray.push("Second Item");
myArray.push("Third Item");
myArray.customProperty = "Hello";
myArray.each(function() {
window.alert(this);
});
Using this new prototype function, ONLY the three items that have been pushed onto the array will be handled by the callback functions (the custom property is ignored). The “this” keyword will point an item in the array. Additionally, there is an index argument in case that’s important to you:
myArray.each(function(index) {
window.alert(this + " is at index " + index);
});

Hi Nick,
You seem to have a pretty good handle on this stuff, and I’m just beginning with javascript. I was hoping you might take the time to walk me through something, what with us both being Riggs’ and all.
I’ve got a function called downloadImage that takes the url, splits it at every ‘/’ symbol, and throws the results into an array. I’d then like to iterate through the array, and split the image name down even further by splitting it at the ‘.”s. Unfortunately, I can’t figure out a way to iterate through the array. Does this sound possible to you? I just started looking at javascript this week, and have no concept of its possibilites and/or limitations.
thx.
November 23, 2009 4:54 pm
@Justin, using the prototype above, sounds like you want something like:
s.split(“/”).each(function() {
this.split(“.”).each(function() {
//this = the string split by “/” then “. ”
});
});
December 2, 2009 10:55 am