The foreach, each, and map traversal array in JS __JS

Source: Internet
Author: User

1.forEach ()

foreach is a method of manipulating arrays in ES5, and the main function is to traverse an array. The function callback in the Foreach method has three parameters: the first argument is the array content of the traversal, the second parameter is the corresponding array index, and the third argument is the array itself

So:

[].foreach (function (value,index,array) {
//code something
});

2.$.each ()

Equivalent to $.each in jquery ():

$.each ([],function (Index,value,array) {
//code something
})

Note that the 1th and 2nd parameters of ForEach () and $.each () are exactly the opposite ...

3.map ()

Map:map is the meaning usage of "mapping" similar to ForEach, which is:

[].map (function (value,index,array) {
//code
})

The map method functions as described above, and the original array is "mapped" to the corresponding new array. The following example is the square of a numeric item

var data=[1,3,4]

var squares=data.map (function (Val,index,arr) {
  console.log (arr[index]==val);  ==> true return
  val*val           
})
Console.log (squares);        ==> [1, 9, 16]

Note: Since both foreach and map are ECMA5 additions to the array, the browsers below IE9 do not support

4. Difference:

The return value is supported in the callback function of the map; What is returned is the equivalent of turning this item in the array into something (without affecting the original array, which is equivalent to cloning the original array and changing the corresponding item in the array of the cloned copy);

ForEach: Used to traverse each item in an array; This method does not have a return value and has no effect on the original array;

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.