1. Method Overview
The map() method returns a new array composed of the return value of each element in the original array called a specified method.
2. Example
2.1 Using map in strings
Use the map method on a String to get an array of ASCII codes corresponding to each character in a string:
var map = Array.prototype.mapvar a = map.call("Hello World", function(x) { return x.charCodeAt(0); })// The value of a is [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]2.2 Prone to making mistakes
Generally speaking, the callback function in the map method only needs to accept one parameter (oftentimes, there is only one custom function parameter), which is the array element itself being traversed.
But this does not mean that map only passes one parameter to callback (it will pass 3 parameters). This thinking inertia may make us a very easy mistake.
// What does the following statement return: ["1", "2", "3"].map(parseInt);// You may think it will be [1, 2, 3]// But the actual result is [1, NaN, NaN]// Usually when using parseInt, you only need to pass one parameter. But in fact, parseInt can have two parameters. The second parameter is a binary number. You can verify it by the statement "alert(parseInt.length)===2".// When the map method calls the callback function, it will pass three parameters: the element currently traversing, the element index, and the original array itself.// The third parameter parseInt will be ignored, But the second parameter does not, that is, parseInt uses the passed index value as a binary number. Thus, it returns NaN./*//The following user function returnIntfunction returnInt(element){ return parseInt(element,10);}["1", "2", "3"].map(returnInt);// Return [1,2,3]*/Reference: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map
A comprehensive understanding of the map() method included in the above article is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.