JavaScript ForEach () traversal function using and introducing _javascript tips

Source: Internet
Author: User

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

}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.