函数Array.prototype.map 需要一个函数作为第一个参数:
var new_array = arr.map(callback[, thisArg])
方括号表示第二个参数是可选的。您可以调用Array.prototype.map,带或不带第二个参数。两个函数调用都有效:
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));
最后同
console.log(array.map(myFuncUsingThis.bind(myThisArg)));
因此,如果您提供给Array.prototype.map 的函数使用this 对象,则可以在Array.prototype.map 调用该函数时使用第二个(可选)参数指定该函数的this 对象。
currentValue、index 和 array 是完全不同的东西。当您致电Array.prototype.map 时,您不必提供它们。相反,Array.prototype.map 为您提供了它们:它使用这三个参数调用您提供给它的函数(但您不必使用所有三个参数)。
函数的第一个参数是当前正在处理的数组中元素的值,第二个参数是该元素的索引,第三个参数是数组本身。
您可以编写一个使用索引参数的函数:
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);
如果您看一下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;
};