The foreach in JavaScript

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, that is, the value of the array).

1 vardata=[1,2,3,4,5,6];2 varSum=0;3Data.foreach (function(v) {//where V is the value of the array 1234564sum+=v;})5document.write (sum+ "6");//printed out is7Data.foreach (function(O,P,Q) {//corresponding to: array element, element index, array itself8Q[p]=o+1;9 })Tendocument.write (data);

Note: foreach cannot terminate before all elements are passed to the called function (whereas for loops have a break method), and if you want to terminate prematurely, you must put foreach in the try block and throw an exception. If the function called by foreach () throws a Foreach.break exception, the loop terminates prematurely:

1 functionforeach (a,b,c) {2 3 Try{4 5 A.foreach (b,c);6 7}Catch(e) {8 9 if(E===foreach. Break)return;Ten  One Else Throwe; A  - } -  the  -  -Foreach. Break=NewError ("Stopiteration"); -  +}

The foreach in JavaScript

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.