Welcome to the nether realm of JavaScript extensions… things that should exist and sometimes kind of do, but with a different name and an inconsiderate API.
Part 6 of 256 Useful JavaScript Extensions Array#each.
/**
* Call the given iterator once for each element in the array,
* passing in the element as the first argument, the index of
* the element as the second argument, and this array as the
* third argument.
*
* @param {Function} iterator Function to be called once for
* each element in the array.
* @param {Object} [context] Optional context parameter to be
* used as `this` when calling the iterator function.
*
* @returns `this` to enable method chaining.
*/
Array.prototype.each = function(iterator, context) {
if(this.forEach) {
this.forEach(iterator, context);
} else {
var len = this.length;
for(var i = 0; i < len; i++) {
iterator.call(context, this[i], i, this);
}
}
return this;
};
You’ll notice that this method makes use of the possibly existing Array#forEach method if it exists. In fact it is almost an alias of it, but since forEach always returns undefined like a jerk, we need to wrap it and return the object for chaining like a good citizen. Also, who wants to always be writing forEach, why not just each? Yeah… I like this.
// Example:
var people = [{name: "David"}, {name: "Joe"}, {name: "Gandalf"}];
// Greet each person by name
people.each(function(person) {
alert("Hi " + person.name + "!");
});


One thought on “Useful JavaScript Game Extensions: Array#each”