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, the value of the array).
var data=[1,2,3,4,5,6];
var sum=0;
Data.foreach (function (v) {//V is the value of the array 123456
sum+=v})
document.write (sum+ "<br>");//Print Out is
data.foreach (function (o,p,q) {//correspond respectively: array element, index of element, array itself
q[p]=o+ 1;
})
document.write (data);
Note: foreach cannot terminate before all elements are passed to the calling function (while the For loop has a break method), if you want to terminate prematurely, you must place the foreach in a try block and throw an exception. If a function called by a foreach () throws a 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");
}