The function Array.prototype.map
expects a function as the first argument:
var new_array = arr.map(callback[, thisArg])
The square brackets indicate that the secondparameter is optional. You can call Array.prototype.map
with or without a second argument. Both functions calls are valid:
var array = [1, 2, 3, 4];
var myFunc = function (number) {
return number * 5;
};
var myFuncUsingThis = function (number) {
console.log(this);
return number;
};
var myThisArg = {
foo: 'bar'
};
console.log(array.map(myFunc));
console.log(array.map(myFuncUsingThis, myThisArg));
The last is the same as
console.log(array.map(myFuncUsingThis.bind(myThisArg)));
So, if the function that you provide to Array.prototype.map
uses the this
object, you can specify the this
object of the function when it is called by Array.prototype.map
by using the second (optional) argument.
currentValue
, index
and array
are something completely different. You do not have to provide them when you call Array.prototype.map
. Instead, Array.prototype.map
provides them for you: it calls the function that you gave it with those three arguments (but you don't have to use all three arguments).
The first argument to your function is the value of the element in the array that is currently processed, the second argument is the index of that element, and the third argument is the array itself.
You can write a function that takes use of the index parameter:
var array = Array(20).fill(0); // an array containing 20 zeros
var evenNumbers = array.map(function (number, index) {
// number is zero, index is the index of the element we should transform
return index * 2;
});
console.log(evenNumbers);
Maybe it helps if you take a look at a (naïve) implementation of Array.prototype.map
:
Array.prototype.map = function (callback, thisArg) {
// "this" is the array on which we work
var arr = []; // the new array that we build
var result;
for (var i = 0; i < this.length; i += 1; i++) {
result = callback.call(thisArg, this[i], i, this);
arr[i] = result;
}
return arr;
};