This first one is most suitable. Repeating one level for each element of the array may make sense in a functional language, but in the language of procedures without tail tail optimization, this is crazy.
However, Array already has a map function: it is defined by ECMA-262 Fifth Edition and, as a built-in function, would be the best choice. Use this:
alert([1,2,3].map(function(n) { return n+3; }));
The only problem is that Fifth Edition is not supported by all current browsers: in particular, Array extensions are not available in IE. But you can fix this with a little correction work on the Array prototype:
if (!Array.prototype.map) { Array.prototype.map= function(fn, that) { var result= new Array(this.length); for (var i= 0; i<this.length; i++) if (i in this) result[i]= fn.call(that, this[i], i, this); return result; }; }
This version, according to the ECMA standard, allows you to pass an optional object to bind to this in a function call and skips any missing values ββ(for this, JavaScript has a list of length 3, where there is no second element).
source share