先來實現一個遍曆Array的forEach函數:
1 function foreach(array, func) { 2 for (var i = 0; i < array.length; i++) { 3 func(array[i]); 4 } 5 } 6 7 function logPrint(element) { 8 console.log(element); 9 }10 11 forEach([2, 5, 7], logPrint); 12 //outputs:13 //214 //515 //7
filter:
1 function filter(func, array) { 2 var result = []; 3 4 forEach(array, function(element){ 5 if (func(element)) { 6 result.push(element); 7 } 8 }); 9 10 return result;11 }12 13 function gtZero(element) {14 if (x > 0) {15 return true;16 }17 }18 19 filter(gtZero, [3, -2, 0, 5]);20 //[3, 5]
map:
function map(func, array) { var result = []; forEach(array, function(element) { result.push(func(element)); }); return result;}function add1(element) { return element+ 1;}map(add1, [0, 2, 4, 6, 8, 10]);//[1, 3, 5, 7, 9, 11]
reduce:
function reduce(func, init, array) { forEach(array, function(element) { init = func(init, element); }); return init;}function add(element1, element2) { return element1 + element2;}reduce(add, 0, [1, 2, 3, 4]);//10
在ECMAScript5的Array中已經有了Array.prototype.forEach,Array.prototype.filter,Array.prototype.map等方法,
請參考http://www.ecma-international.org/ecma-262/5.1/#sec-15.4。