12Aug/094
A simple map function for plain JavaScript arrays
So this isn't anything new, but sometimes you have to work with plain JavaScript and can't lean on a library. I thought I'd put this out there. This is my map function. There are many like it, but this one is mine.
CODE:
-
Array.prototype.map = function(fn) {
-
var r = [];
-
var l = this.length;
-
for(i=0;i<l;i++)
-
{
-
r.push(fn(this[i]));
-
}
-
return r;
-
};
note bene: Why do I declare the "l" variable at all instead of just checking i against this.length directly? The JavaScript for loop is much faster if you don't perform the length lookup and instead check against a static value.

August 12th, 2009 - 13:14
Its called “manual hoisting”
Cheers,
Greg
August 12th, 2009 - 14:35
What about sparse arrays? (ok, maybe they’re rare on the wild) How about for … in to loop through?
August 12th, 2009 - 16:44
Very useful. (I have a similar implementation myself.) By the way, I’ve used this sort of syntax for loops:
for (int idx = 0, len = arr.length; idx++; idx < len) {
…
}
August 12th, 2009 - 20:23
Duncan: with a for-in loop and a JavaScript array, you end up looping over all members of the Array type. If you have modified the prototype of the native Array, you’ll end up iterating over them as well. See this post for a better explanation as well as a way to avoid that.
http://www.lazycoder.com/weblog/2008/05/23/modern-javascript-development-reflection-in-javascrpt/
edit: Ok, that post I linked to helps if you are dealing with objects that are not native JavaScript objects. Native JavaScript objects are a little bit different. The members of native JavaScript objects are marked as non-enumerable, so for-in works on them provided that their prototype object has not been modified. If it has, you’ll have to use a combination of the technique described in the post aboce as well as special casing out the members you know have been added to the native JavaScript object.