OK, so the Array.prototype.map( ) in JavaScript, pretty simple one, but today I was stucked by this for more than three hours.
We are already getting used to the most basic function of this Map( ) function of JS.
Basic Function
var array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2); // pass a function to map
console.log(map1); // expected output: Array [2, 8, 18, 32]
Well, this is not the whole story yet, let's look deep into the definition on MDN
Here are the important points:
it could have as many as THREE parameters: the value of the element, the index of the element, and the Array object being traversed.
it returns a new array
Sometimes when we use Map( ), it passes the second and third parameters automatically, and then creates problems.
Example with Two parameters
Using the example from the MDN website for better understanding
["1", "2", "3"].map(parseInt); // result is [1, NaN, NaN];
first, let's take a look at the definition of parseInt from MDN
parseInt(string, radix);
string
The value to parse. If this argument is not a string, then it is converted to one using the ToString abstract operation. Leading whitespace in this argument is ignored.
radix
An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. Be careful — this does not default to 10.
Therefore, parseInt( ) function needs two parameters. Combining with map( ) function, the array will pass the first two parameters to parseInt( ) function automatically.
// parseInt(string, radix) -> map(parseInt(value, index))
/* first iteration (index is 0): */ parseInt("1", 0); // 1
/* second iteration (index is 1): */ parseInt("2", 1); // NaN
/* third iteration (index is 2): */ parseInt("3", 2); // NaN
If we also consider about the Third Parameter, the array itself, the following example might be more clear.
OK, so the Array.prototype.map( ) in JavaScript, pretty simple one, but today I was stucked by this for more than three hours.
We are already getting used to the most basic function of this Map( ) function of JS.
Basic Function
Well, this is not the whole story yet, let's look deep into the definition on MDN
Here are the important points:
Sometimes when we use Map( ), it passes the second and third parameters automatically, and then creates problems.
Example with Two parameters
Using the example from the MDN website for better understanding
first, let's take a look at the definition of parseInt from MDN
Therefore, parseInt( ) function needs two parameters. Combining with map( ) function, the array will pass the first two parameters to parseInt( ) function automatically.
If we also consider about the Third Parameter, the array itself, the following example might be more clear.
Example with Three Parameters
The third parameter is not used very often, but the first two could be applied into projects and might bring some convenience.