Use and introduction of the JavaScript forEach () traversal function, javascriptforeach
The forEach () function traverses the array from start to end. There are three parameters: array element, element index, and array (if a parameter is an array element, it is the value of the array.
Var data = [1, 2, 3, 4, 5, 6]; var sum = 0; data. forEach (function (v) {// where v is the array value 123456sum + = v;}) document. write (sum + "<br>"); // print out 21data. forEach (function (o, p, q) {// corresponds to array elements, element indexes, array itself q [p] = o + 1;}) document. write (data );
Note: forEach cannot terminate before all elements are passed to the called function (while the for loop has a break method). To terminate the function in advance, you must put forEach in the try block, and can throw an exception. If a forEach. break exception is thrown by a function called by foreach (), the loop is terminated in advance:
Function foreach (a, B, c) {try {. forEach (B, c);} catch (e) {if (e = foreach. break) return; else throw e ;}} foreach. break = new Error ("StopIteration ");}