JavaScript in Array.prototype.map () detailed

Source: Internet
Author: User
Tags array length

The map method invokes the callback function sequentially for each element in the original array. Callback the return value after each execution is combined to form a new array. The callback function is only called on the indexed index, and those indexes that have never been assigned a value or deleted by using Delete are not called.

In our daily development, manipulating and converting arrays is a very common operation, let's look at an example:

Copy CodeThe 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);


As can be seen from the above example, all the operating repetition rate is relatively high, how to optimize it, fortunately ECMAScript 5 gives us a map method, we can use it to optimize the above example:

Copy CodeThe 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);

As we can see from the example above, we have replaced the for loop part with map, so we only need to care about the implementation logic of each element itself. For details on the map method, please poke here.

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

The map method invokes the callback function sequentially for each element in the original array. Callback the return value after each execution is combined to form a new array. The callback function is only called on the indexed index, and those indexes that have never been assigned a value or deleted by using Delete are not called.

The callback function is automatically passed in three parameters: an array element, an element index, and the original array itself.

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

Map does not modify the original array that invokes it (it can, of course, change the original array when callback executes).

When an array runs the map method, the length of the array is determined before the first callback method is called. During the entire operation of the map method, the element is added or deleted regardless of whether the operation in the callback function gives the original array. The map method does not know that if an array element is added, the newly added element will not be traversed by the map, and if the array element is reduced, the map method will also assume that the original array length has not changed, resulting in array access beyond the bounds. If the elements in the array are changed or deleted, then the value of their incoming callback is the value that the map method traverses to their moment.

2.map instance:

Copy CodeThe code is as follows:
Instance one: Call the Map method on a 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", "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 example above demonstrates using the map method on a string to get an array of ASCII code for each character in the string. Note the results of the printed console.log (arr) print.

Copy CodeThe code is as follows:
Example two: What is the result of the following operation?
var result = ["1", "2", "3"].map (parseint);
Outputs: [1, Nan, Nan]
Console.log (result);

Maybe you have questions, why not [All-in-one]? We know that the parseint method can receive two parameters, the first parameter is the value that needs to be converted, the second argument is the binary number, and the unknown can be poked here. When we use the map method, the callback function receives three parameters, and parseint can receive up to two parameters, so that the third parameter is discarded directly, and at the same time, Parseint uses the passed index value as a binary number. This returns NAN. Look at the following output:

Copy CodeThe 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 next two are easy to understand, but why did the first two return 1? To explain the problem, 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 are (hexadecimal) and the remainder of the string is parsed.
b) If the input string begins with "0″, Radix is eight (octal) or (decimal). Exactly which Radix is chosen is implementation-dependent. ECMAScript 5 Specifies (decimal) is used, and not all browsers support this yet. For the reason always specify a radix when using parseint.
c) If the input string begins with any and value, the Radix is (decimal).
In the 3rd, when string is a different value, the binary default is 10.

So how can we change the normal output of the above example? Look at the following example:

Copy CodeThe code is as follows:
var result = ["1", "2", "3"].map (val) {
Return parseint (Val, 10);
});
Outputs: [1, 2, 3]
Console.log (result);

Compatibility of 3.map methods:
The map method is not supported in IE8 and the following browsers, in order to be compatible with the old version of the browser, you can:

a) Don ' t use map . b) Use something like Es5-shim to make older IE's support map . c) Use the _.map method in underscore O R Lodash for an equivalent utility function.

JavaScript in Array.prototype.map () detailed

Related Article

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.