Home >Web Front-end >JS Tutorial >JavaScript forEach() traversal function usage and introduction_javascript skills

JavaScript forEach() traversal function usage and introduction_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:50:531506browse

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

}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn