JS foreach and map usage

Source: Internet
Author: User
ForEach:

foreach is the most basic one of the new array methods in ECMA5, that is, traversal, loop. For example, the following example:
[1, 2, 3, 4].foreach (alert);
Equivalent to the following for loop:

var array = [1, 2, 3, 4];
for (var i = 0, length = Array.Length i < length; i++) {
 alert (array[i]);

The function callback in the Foreach method supports 3 parameters, the 1th is the array content that is traversed, the 2nd is the corresponding array index, and the 3rd is the array itself.

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

For example:

var array = [1,2,3];
Array.foreach (function (Val,index,arr) {
    console.log (' val: ' +val); => 1,2,3 console.log
    ("index:" + index); =>0,1,2
    Console.log (arr); => [1,2,3]
})
output in the console is:

Because foreach is essentially a loop, it outputs three of times an array.


Map:

The map method of an array refers to the mapping, in which the original array is "mapped" to the corresponding new array.

Array.map (callback,[thisobject]);

Use of Map:
Map receives three parameters like foreach, and he can map the original array to the new array.

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: These two methods are not supported by browsers below IE9, and can be expanded from the array prototype to achieve all of these functions:

if (typeof Array.prototype.forEach!= "function") {
  Array.prototype.forEach = function () {/
    * Custom Function Implementation * * * *
  };< c10/>}

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.