ECMAScript 5 defines 5 iterative methods for an array. Each method receives two parameters: the function to run on each item and, optionally, the scope object that runs the function-the value that affects this.
The functions passed into these methods receive three parameters: the value of the array item , the position of the item in the array , and the array object itself .
The following are the 5 iterative methods that work:
- Every (): Runs the given function for each item in the array, and returns True if the function returns true for each item .
- Some (): Runs the given function for each item in the array, and returns True if the function returns true for either item .
1 varnumbers = [1,2,3,4,5,4,3,2,1]; 2 3 varEveryresult = Numbers.every (function(item, index, array) {4 return(Item > 2); 5 }); 6 7alert (Everyresult);//false8 9 varSomeresult = Numbers.some (function(item, index, array) {Ten return(Item > 2); One }); A -alert (Someresult);//true
- Filter (): Each item in an array runs the given function, and returns a list of items that are true of the function.
1 var numbers = [1,2,3,4,5,4,3,2,1]; 2 3 var filterresult = Numbers.filter (function(item, index, array) { 4 return (Item > 2); 5 }); 6 7 alert (filterresult); //
- ForEach (): Runs the given function for each item in the array. This method has no return value.
1 var numbers = [1,2,3,4,5,4,3,2,1]; 2 3 Numbers.foreach (function(item, index, array) { 4 // perform certain actions 5 });
- Map (): Each item in the array runs the given function, returning an array that consists of the results of each function call.
1 var numbers = [1,2,3,4,5,4,3,2,1]; 2 3 var mapresult = Numbers.map (function(item, index, array) { 4 Return Item * 2; 5 }); 6 7 alert (mapresult); // [2,4,6,8,10,8,6,4,2]
The browsers that support these iterations are ie9+, Firefox, Safari, Opera 9.5+ and Chrome.
An iterative approach to the type of JavaScript arrays (array)