JavaScript Array.prototype.map () basic knowledge

Source: Internet
Author: User

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

Copy Code code 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 we can see from the above example, all of the operating repetition rate is relatively high, how to optimize it, fortunately ECMAScript 5 provides us with a map method, we can use it to optimize the example:

Copy Code code 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 example above, we use map to replace the part of the For loop so that we only need to care about the implementation logic of each element itself. For more information on the map method, please stamp here.

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

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

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 this object on the Thisarg parameter each time the callback function is invoked. If the Thisarg argument is omitted, or if the assignment is null or undefined, this points to the global object.

The map does not modify the original array that called it (of course it can 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 invoked. During the entire run 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 incremented, the newly added element is not traversed by the map, and if the array element is reduced, the map method also considers the length of the original array unchanged, causing array access to cross bounds. If the elements in the array are changed or deleted, the value they are passed into callback is the value of the map method traversing to their moment.

2.map instance:

Copy Code code as follows:

Instance one: Calling 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", Ten: "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 previous example demonstrates using the map method on a string to get an array of ASCII codes for each character in the string. Note the results of the printed console.log (arr) print.

Copy Code code 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 a question, why not [1,2,3]? We know that the parseint method can receive two parameters, the first parameter is the value that needs to be converted, the second parameter is the number of the binary, and the unknown can be stamped here. When we use the map method, the callback function receives three parameters, while the parseint receives up to two parameters, so that the third argument is discarded directly, while parseint uses the passed index as a number of numbers. Thus returning Nan. Look at the following output:

Copy Code code 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 were 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 that's used, but not all browsers support the this yet. For this reason always specify a radix when using parseint.
c) If the input string begins with any other value and the Radix is (decimal).
In the 3rd, when string is a different value, the system defaults to 10.

So how do we modify to make the above example normal output? Look at the following example:

Copy Code code as follows:

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

3.map method Compatibility:
The map method is not supported in IE8 and the following browsers, and to be compatible with older browsers, you can:

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

The above is the map method of understanding, I hope to help beginners, the text in the wrong place, but also hope treatise!

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.