First, implement a foreach function that traverses the array:
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 // 2 14 // 5 15 // 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:
FunctionMap (func, array ){VaRResult =[]; Foreach (array,Function(Element) {result. Push (func (element ));});ReturnResult ;}FunctionAdd1 (element ){ReturnElement + 1;} Map (Add1 ,[0, 2, 4, 6, 8, 10]);//[1, 3, 5, 7, 9, 11]
Reduce:
FunctionReduce (func, init, array) {foreach (array,Function(Element) {init=Func (init, element );});ReturnInit ;}FunctionAdd (element1, element2 ){ReturnElement1 +Element2;} reduce (add,0, [1, 2, 3, 4]);//10
The array. Prototype. foreach, array. Prototype. filter, array. Prototype. Map, and other methods are available in the array of ecmascript5,
See http://www.ecma-international.org/ecma-262/5.1/eclipsec-15.4.