Home > Article > Web Front-end > JavaScript forEach() traversal function usage and introduction_javascript skills
The forEach() function traverses the array from beginning to end. There are three parameters: array element, element index, and array itself (if it is a parameter, it is the array element, which is the value of the array.
var data=[1,2,3,4,5,6]; var sum=0; data.forEach(function(v){//其中的v就是数组的值 123456 sum+=v;}) document.write(sum+"<br>");//打印出来是21 data.forEach(function(o,p,q){//分别对应:数组元素,元素的索引,数组本身 q[p]=o+1; }) document.write(data);
Note: forEach cannot be terminated before all elements are passed to the called function (but the for loop has a break method). If you want to terminate early, forEach must be placed in a try block and an exception can be thrown. If the function called by forEach() throws a foreach.break exception, the loop will terminate early:
function foreach(a,b,c){ try{ a.forEach(b,c); }catch(e){ if(e===foreach.break)return; else throw e; } } foreach.break=new Error("StopIteration"); }