The ForEach () function iterates through the array from beginning to end. There are three parameters: the array element , the index of the element , the array itself (if a parameter is an array element, that is, the value of the array).
1 vardata=[1,2,3,4,5,6];2 varSum=0;3Data.foreach (function(v) {//where V is the value of the array 1234564sum+=v;})5document.write (sum+ "6");//printed out is7Data.foreach (function(O,P,Q) {//corresponding to: array element, element index, array itself8Q[p]=o+1;9 })Tendocument.write (data);
Note: foreach cannot terminate before all elements are passed to the called function (whereas for loops have a break method), and if you want to terminate prematurely, you must put foreach in the try block and throw an exception. If the function called by foreach () throws a Foreach.break exception, the loop terminates prematurely:
1 functionforeach (a,b,c) {2 3 Try{4 5 A.foreach (b,c);6 7}Catch(e) {8 9 if(E===foreach. Break)return;Ten One Else Throwe; A - } - the - -Foreach. Break=NewError ("Stopiteration"); - +}
The foreach in JavaScript