Use and introduction of the JavaScript forEach () traversal function, javascriptforeach

Source: Internet
Author: User

Use and introduction of the JavaScript forEach () traversal function, javascriptforeach

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 array value 123456sum + = v;}) document. write (sum + "<br>"); // print out 21data. forEach (function (o, p, q) {// corresponds to array elements, element indexes, 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 {. 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.