Home > Web Front-end > JS Tutorial > body text

JavaScript forEach() traversal function usage and introduction_javascript skills

WBOY
Release: 2016-05-16 15:50:53
Original
1473 people have browsed it

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);
Copy after login

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

}
Copy after login


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!