JS Array Map method

Source: Internet
Author: User

Map
Here is map not the meaning of "map", but refers to "mapping". The [].map(); basic usage is similar to the forEach method:

Array.map (callback,[thisobject]);

callbackThe parameters are similar:

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

mapThe function of the method is not difficult to understand, "mapping", that is, the original array is "mapped" into a corresponding new array. The following example is the value of the square:

var data = [1, 2, 3, 4];var arrayofsquares = Data.map (function (item) {  //1, 4, 9,

callbackNeed to have a return value, if not, just like this:

var data = [1, 2, 3, 4];var arrayofsquares = Data.map (function () {}); Arrayofsquares.foreach (Console.log);

As a result, as you can see, all the items in the array are mapped undefined :

In practical use, we can make use of the map method to obtain the specific attribute values in the object array conveniently. For example, the following example is also the example of a compatible demo:

var users = [  {name: "Zhang contains rhyme", "email": "[email protected]"},  {name: "Dancing Dogs",   "email": "[email protected]"},  {name: "Li Xiaolu",  //[email protected], [email protected], [email protected]

Array.prototypeExtensions allow IE6-IE8 browsers to also support map methods:

if (typeof Array.prototype.map! = "function") {  Array.prototype.map = function (FN, context) {    var arr = [];    if (typeof fn = = = "function") {      for (var k = 0, length = this.length; k < length; k++) {               Arr.push (Fn.call (conte XT, This[k], K, this));      }    }    return arr;  };}

JS Array Map method

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.