JavaScript iterates through the array, executes the FN function for each element in the array, and passes the array index and elements as parameters

Source: Internet
Author: User

There are two main methods of traversal, i++ method and in keyword method

varlist = [1, 2, 3, 4, 5, 6,7,8];//var L = list.length; for(varIinchlist) {Console.log (list[i]);}//[finished in 0.3s]varlist = [1, 2, 3, 4, 5, 6,7,8];//var L = list.length; for(vari = 0; i < list.length; i++) {Console.log (list[i]);}//[finished in 0.5s]varlist = [1, 2, 3, 4, 5, 6,7,8];varL =list.length; for(vari = 0; I < L; i++) {Console.log (list[i]);}//[finished in 0.4s]

It is relatively more efficient to

functionEach (arr, fn) {//your implement   for(Indexincharr)  {fn (arr[index],index); }}//where the FN function can accept two parameters: item and Index//using the examplevararr = [' Java ', ' C ', ' php ', ' HTML '];functionoutput (item) {Console.log (item)}each (arr, output); //Java, C, PHP, HTML//using the examplevararr = [' Java ', ' C ', ' php ', ' HTML '];functionoutput (item, index) {console.log (index+ ': ' +Item)}  Each (arr, output); //0:java, 1:c, 2:php, 3:html

However, the actual output format and expectations are different and are still to be improved.

JavaScript iterates through the array, executes the FN function for each element in the array, and passes the array index and elements as parameters

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.