"Turn" talking about the foreach and each in JavaScript

Source: Internet
Author: User

foreach is a method of manipulating an array in ES5, and the main function is to iterate through the array, for example:

1 var arr = [1,2,3,4]; 2 Arr.foreach (alert);

Equivalent to:

1 var arr = [1, 2, 3, 4]; 2  for (var k = 0, length = arr.length; k < length; k++) {3  alert (array[k]); 4 }

The function callback in the Foreach method has three parameters: the first argument is the array contents of the traversal, the second parameter is the corresponding array index, and the third parameter is the array itself

So:

1 [].foreach (function(value,index,array) {2  3//  Code something4  5 });     

Equivalent to:

1 $.each ([],function(index,value,array) {2  3//  code something4  5 })    

Write an example;

1 var arr = [1,2,3,4]; 2 Arr.foreach (function(value,index,array) {3     array[index] = = value;    // result is true 4     sum+=value;   5     }); 6 console.log (sum);    // The result is ten

Map:map is a "map" that uses the same meaning as a forEach, using the following:

1 [].map (function(value,index,array) {2  3//code  4  5 })   

Reference Documentation:

Https://www.cnblogs.com/fangshidaima/p/5910604.html

"Turn" talking about the foreach and each 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.