JavaScript array map function
October 07, 2010 19:20:55 Last update: January 11, 2011 19:59:17
Like the string trim function, Firefox provides a native implementation for array map, IE doesn't. So we have to create our own
Test page:
map function for Array:
if(typeof Array.prototype.map !== 'function') { Array.prototype.map = function(fn) { for (i=0, r=[], l = this.length; i < l; r.push(fn(this[i++]))); return r; }; }
Test page:
- Code
- Demo
<html> <head> <title>Array Map</title> </head> <body> <script language="javascript" type="text/javascript"> if(typeof Array.prototype.map !== 'function') { Array.prototype.map = function(fn) { for (i=0, r=[], l = this.length; i < l; r.push(fn(this[i++]))); return r; }; } var original = ['1', '2', '3', '4']; document.write('<b>Original items:</b><br>'); document.write('======================<br>'); for (var i = 0; i < original.length; i++) { document.write(original[i] + '<br>'); } var mapped = original.map(function(i) { return 'div' + i; }); document.write('<br><b>Mapped items</b><br>'); document.write('======================<br>'); for (var i = 0; i < mapped.length; i++){ document.write(mapped[i] + '<br>'); } </script> </body> </html>