Use and introduction of JavaScript forEach of Traversal function

  • 2020-07-21 06:47:18
  • OfStack

The forEach() function iterates through the array 1. There are three parameters: the array element, the index of the element, and the array itself (if 1 parameter is an array element, that is, the value of the array.


var data=[1,2,3,4,5,6];
var sum=0;
data.forEach(function(v){// One of the v That's the value of the array  123456
sum+=v;})
document.write(sum+"<br>");// It's printed out as 21
data.forEach(function(o,p,q){// Corresponding to: array element, element index, array itself 
 q[p]=o+1;
})
document.write(data);

Note: forEach cannot terminate before all elements are passed to the calling function (whereas the for loop has break methods). To terminate early, you must place forEach in the try block and be able to throw an exception. If the function called by forEach() throws an foreach.break exception, the loop terminates prematurely:


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");

}



Related articles: