Array. prototype. map () in Javascript _ basic knowledge-js tutorial

Source: Internet
Author: User
The map method calls the callback function once in order for each element in the original array. The returned values after each callback operation are combined to form a new array. The callback function is called only on indexes with values. indexes that have never been assigned or deleted using delete are not called. In our daily development, operations and conversion of arrays are common operations. Let's look at an example:

The Code is as follows:


Var desColors = [],
SrcColors = [
{R: 255, g: 255, B: 255}, // White
{R: 128, g: 128, B: 128}, // Gray
{R: 0, g: 0, B: 0} // Black
];

For (var I = 0, ilen = srcColors. length; I <ilen; I ++ ){
Var color = srcColors [I],
Format = function (color ){
Return Math. round (color/2 );
};

DesColors. push ({
R: format (color. r ),
G: format (color. g ),
B: format (color. B)
});
}

// Outputs:
//[
// {R: 128, g: 128, B: 128 },
// {R: 64, g: 64, B: 64 },
// {R: 0, g: 0, B: 0}
//];
Console. log (desColors );


From the above example, we can see that all operations have a high repetition rate. How can we optimize it? Fortunately, Ecmascript 5 provides us with a map method, which we can use to optimize the above example:

The Code is as follows:


Var srcColors = [
{R: 255, g: 255, B: 255}, // White
{R: 128, g: 128, B: 128}, // Gray
{R: 0, g: 0, B: 0} // Black
],
DesColors = srcColors. map (function (val ){
Var format = function (color ){
Return Math. round (color/2 );
};
Return {
R: format (val. r ),
G: format (val. g ),
B: format (val. B)
}
});
// Outputs:
//[
// {R: 128, g: 128, B: 128 },
// {R: 64, g: 64, B: 64 },
// {R: 0, g: 0, B: 0}
//];
Console. log (desColors );

From the above example, we can see that we replaced the for loop with map, so we only need to care about the implementation logic of each element. For details about the map method, click here.

1. Basic map definition:
Array. map (callback [, thisArg]);

The map method calls the callback function once in order for each element in the original array. The returned values after each callback operation are combined to form a new array. The callback function is called only on indexes with values. indexes that have never been assigned or deleted using delete are not called.

The callback function is automatically passed in three parameters: array elements, element indexes, and the original array.

If the thisArg parameter has a value, this will point to this object on the thisArg parameter each time the callback function is called. If the thisArg parameter is omitted, or the value is null or undefined, this points to the global object.

Map does not modify the original array itself that calls it (of course, the original array can be changed when callback is executed ).

When an array runs the map method, the length of the array is determined before the first callback method is called. During the whole operation of the map method, no matter whether the operation in the callback function adds or deletes elements to or from the original array. The map method does not know. If the array element is added, the newly added element is not traversed by the map. If the array element is reduced, the map method considers the length of the original array unchanged, as a result, array access is out of bounds. If the elements in the array are changed or deleted, the callback value is the value when the map method traverses them.

2. map instance:

The Code is as follows:


// Instance 1: Call the map method on the string
Var result = Array. prototype. map. call ("Hello world", function (x, index, arr ){
// String {0: "H", 1: "e", 2: "l", 3: "l", 4: "o", 5 :"", 6: "w", 7: "o", 8: "r", 9: "l", 10: "d", length: 11}
Console. log (arr );
Return x. charCodeAt (0 );
});
// Outputs: [72,101,108,108,111, 32,119,111,114,108,100]
Console. log (result );

The preceding example demonstrates how to use the map method on a String to obtain an array consisting of the ASCII code corresponding to each character in the String. Check the output of the printed console. log (arr.

The Code is as follows:


// Instance 2: What are the following operation results?
Var result = ["1", "2", "3"]. map (parseInt );
// Outputs: [1, NaN, NaN]
Console. log (result );

Maybe you have questions. Why not [1, 2, 3? We know that the parseInt method can receive two parameters. The first parameter is the value to be converted, and the second parameter is the hexadecimal number. If you do not know it, You can stamp it here. When we use the map method, the callback function receives three parameters, while the parseInt can only receive two parameters at most, so that the third parameter is discarded directly, parseInt uses the passed index value as the base number. then NaN is returned. See the following output:

The Code is as follows:


// Ouputs: 1
Console. log (parseInt ("1", 0 ));
// Ouputs: 1
Console. log (parseInt ("1", undefined ));
// Ouputs: NaN
Console. log (parseInt ("2", 1 ));
// Ouputs: NaN
Console. log (parseInt ("3", 2 ));

The last two are easy to understand, but why does the first two return 1? To explain this question, let's look at the official description:
If radix is undefined or 0 (or absent), JavaScript assumes the following:
A) If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.
B) If the input string begins with "0", radix is eight (octal) or 10 (decimal ). exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. for this reason always specify a radix when using parseInt.
C) If the input string begins with any other value, the radix is 10 (decimal ).
In the third point, when the value of string is another value, the default value is 10.

So how can we modify it to make the previous example output normally? See the following example:

The Code is as follows:


Var result = ["1", "2", "3"]. map (function (val ){
Return parseInt (val, 10 );
});
// Outputs: [1, 2, 3]
Console. log (result );

3. Compatibility of map methods:
The map method is not supported in IE8 and earlier browsers. To be compatible with earlier browsers, you can:

A) Don't usemap. B) Use something like es5-shim to make older IE's supportmap. C) Use_.mapMethod in Underscore or Lodash for an equivalent utility function.

The above is an understanding of the map method. I hope it will be helpful to beginners. What's wrong with this article is that I hope it will be an axe!

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.