I know it’s a matter of taste, but for my taste using for loop each time I want to iterate over array is bad. So I came up with this:
Array.prototype.each = function(callback) {
for (var i = 0; i < this.length; i++)
callback(this[i]);
}
Now I can do:
[10, 20, 30].each(function(n) { console.log(n/10) })
Later I found some tips on the Internet that suggested this approach, but I still wonder if it’s free from side effects. It seems very obvious, and that is what worries me 🙂
I’m not using any library like jQuery or Prototype. I’m coding for Node.js.
I suggest you use
forEach. It’s implemented in most modern browsers, and the shim is provided by MDN.On node.js, it’s implemented (it uses V8, same engine as Chrome), so you don’t need a shim.
Its use is something like the following:
Also, I suggest you look at the new array methods provided by ES5: