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:
arr.forEach( function( el ) {
// play with "el"
} )
Also, I suggest you look at the new array methods provided by ES5:
This does have a pretty big side effect
If we now run the following code
a = [10, 20, 30];
for (var i in a) {
console.log(i + ": " + a[i]);
}
And check the console output, we see this:
0: 10
1: 20
2: 30
each: function (callback) {
for (var i = 0; i < this.length; i++)
callback(this[i]);
}
Which restricts the type of for loop you can do on an array to
a = [10, 20, 30];
for (var i = 0; i < a.length; ++i) {
console.log(a[i] + ": " + a[i]);
}