Browser compatibility: ie9+
ES5 defines 5 iterative methods for an array. Each of these methods receives two parameters. The function to run on each item and (optionally) the scope object that runs the function--affects the value of this. where (optional) This parameter has not been encountered for the time being.
Where the function receives three parameters (each item in the array, the index value of each item, the array object itself).
The following is an introduction to the methods in 5:
Every (): Performs a function on each item in an array, and returns TRUE if each item returns TRUE.
Some (): Performs a function on each item in an array, and returns True if one of the items returns true.
Filter (): Performs a function on each item in the array, returning the item that returns true to an array.
ForEach () executes a function on each item in an array, with no return value. Similar to a For loop.
Map () Executes the function for each item in the array, returning (after processing) each item.
None of the above 5 methods will change the array itself.
Comparison of foreach and map:
vararr = [1,2,3,4,5]; //every () filter () some () ForEach () map () varres = Arr.every (function(i,index,o) {returnI>2; }); Console.log (arr); //[1,2,3,4,5]Console.log (RES);//false varsome = Arr.some (function(i, K, l) {returnI>2; }); Console.log (arr);//[1,2,3,4,5]Console.log (some);//true varFilter = Arr.filter (function(i, K, l) {returnI>2; }); Console.log (arr);//[1,2,3,4,5]Console.log (filter);//[3,4,5] varForEach = Arr.foreach (function(i, K, l) {returnI>2; }); Console.log (arr);//[1,2,3,4,5]Console.log (ForEach);//undefined varMap = Arr.map (function(i, K, l) {returnI>2; }); Console.log (arr);//[1,2,3,4,5]Console.log (map);//[False,false,true,true,true]
5 ways to iterate arrays in JavaScript