Js forEach, jsforeach

Source: Internet
Author: User

Js forEach, jsforeach
Zookeeper

The forEach () function traverses the array from start to end. There are three parameters: array element, element index, and array (if a parameter is an array element, it is the value of the array.


Var data = [1, 2, 3, 4, 5, 6];
Var sum = 0;
Data. forEach (function (v) {// where v is the value of the array 123456
Sum + = v ;})
Document. write (sum + "<br>"); // print it as 21
Data. forEach (function (o, p, q) {// corresponds to the array elements, element indexes, and the array itself.
Q [p] = o + 1;
})
Document. write (data );


Note: forEach cannot terminate before all elements are passed to the called function (while the for loop has a break method). To terminate the function in advance, you must put forEach in the try block, and can throw an exception. If a forEach. break exception is thrown by a function called by foreach (), the loop is terminated in advance:

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


}

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.