Home > Web Front-end > JS Tutorial > body text

Detailed explanation of Array.prototype.map() in Javascript_Basic knowledge

WBOY
Release: 2016-05-16 16:33:08
Original
1174 people have browsed it

In our daily development, operating and converting arrays is a very common operation. Let’s take a look at an example:

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


As can be seen from the above example, the repetition rate of all operations is relatively high. How to optimize it? Fortunately, Ecmascript 5 provides us with a map method, which we can use to optimize the above example:

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

As can be seen from the above example, we use map to replace the for loop part, so we only need to care about the implementation logic of each element itself. For details on the map method, please click here.

1.map basic definition:
array.map(callback[, thisArg]);

The map method will call the callback function once for each element in the original array in sequence. The return values ​​after each callback execution are combined to form a new array. The callback function will only be called on indexes that have values; indexes that have never been assigned a value or deleted using delete will not be called.

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

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

map does not modify the original array itself (of course the original array can be changed when callback is executed).

When the map method is run on an array, the length of the array is determined before the first callback method is called. During the entire running process of the map method, no matter whether the operation in the callback function adds or deletes elements to the original array. The map method will not know that if the array elements increase, the newly added elements will not be traversed by the map. If the array elements decrease, the map method will also think that the length of the original array has not changed, resulting in an out-of-bounds array access. If elements in the array are changed or deleted, their values ​​passed into the callback are the values ​​at that moment when the map method traverses to them.

2.map instance:

Copy code The code is as follows:

//Example 1: 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", 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 above example demonstrates using the map method on a String to obtain an array consisting of the ASCII codes corresponding to each character in the string. Please pay attention to the results printed by console.log(arr).

Copy code The code is as follows:

//Example 2: 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 [1,2,3]? We know that the parseInt method can receive two parameters. The first parameter is the value that needs to be converted, and the second parameter is the base number. If you don’t understand, you can click here. When we use the map method, the callback function receives three parameters, while parseInt can only receive at most two parameters, so that the third parameter is directly discarded. At the same time, parseInt treats the passed index value as a base number. to use. Thus returning NaN. Look at the output below:

Copy code 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 do the first two return 1? To explain this problem, let’s take a 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 string is another value, the base defaults to 10.

So how can we modify it to make the above example output normally? Look at the following example:

Copy code 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 method:
The map method is not supported in browsers IE8 and below. To be compatible with older versions of browsers, you can:

a) Don't use <font face="NSimsun">map</font>.b) Use something like es5-shim to make older IE's support <font face="NSimsun">map</font>.c) Use the <font face="NSimsun">_.map</font> method in Underscore or Lodash for an equivalent utility function.

The above is my understanding of the map method. I hope it will be helpful to beginners. I hope that any inaccuracies in the article will be corrected!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!