The difference between a foreach and a map in JS

Source: Internet
Author: User

Let's first look at the similarities between the two.

var arr = [' A ', ' B ', ' C ', ' d '];arr.foreach (Item,index,arr) {//item represents each item in the array, index identifies the subscript for the current item, Arr represents the current array    console.log (item);    Console.log (index);    Console.log (arr);    Console.log (this);},123); Here the 123 parameter, which represents the function of this point, can be written without writing, if not written, then this point windowarr.map (function (Item,index,arr) {   //parameter meaning the same as foreach    Console.log (item);    Console.log (index);    Console.log (arr);    Console.log (this);},123);

After running, you can see that there is no difference between the two parameters, in addition to the two there is a feature, is not to stop the inside of the traversal, unless the program error, then the difference between the two there???

is the return value!!!

var a = Arr.foreach (function(item,index,arr) {     return 123}); var b = Arr.map (function(item,index,arr) {    return 123}); Console.log ( a);     // undefinedconsole.log (b);    // [123,123,123,123]

What can we do with this feature of map, like

var b = Arr.map (function(item,index,arr) {    return item+ ' a ';}); Console.log (b); ["AA", "BA", "Ca", "Da"]

foreach is the method introduced in Es3, and map is a method introduced in ES5, and there are still some compatibility issues in the low version of IE.

The difference between a foreach and a map in JS

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.