An each function for JS
sat18feb2006—07w049d13%— 06h28m00s—0utc
Since Javascript 1.2 and later there has been a cool and very powerful literal syntax for functions:
var sum = function(x, y) {return x+y}
A couple of weeks ago I found an interesting use of this syntax. Missing Ruby’s wonderful each function, I decided to implement something similar in JS, and, after some experimentation, ended up with this:
function each(a, f) { for(var i=0, l=a.length; i<l; i++) f(a[i]) };
The function syntax comes in handy when you use this each:
each([1, 2, 3, 4, 5], function((e) { alert(e) }));
It may not be as satisfying as Ruby’s each, but it’s quite useful.