我对在这种情况下如何使用this
关键字感到困惑。它被放置在带有参数回调的匿名函数中,然后使用它:callback(this[i], i, this)
。这个练习没有深入,但据我所知,this
指的是__proto__中的ar
对象。为什么3个参数被放置在匿名函数的参数callback(this[i],i,this)
and中它是如何在引擎盖下工作的?非常感谢任何见解,谢谢。
只是为了补充之前的说法,这个练习要求我实施我自己的Array.prototype.map
版本。
Array.prototype.map = function(callback) {
let arr = [];
for(let i = 0; i < this.length; i++){
arr.push(callback(this[i], i , this))
}
return arr;
}
let ar = new Array()
map
函数将在Array
实例上调用,因此在以下代码行中:
for(let i = 0; i < this.length; i++){
arr.push(callback(this[i], i , this))
}
是根据传递给Array.prototype.map
方法的回调函数的签名:
callback生成新数组元素的函数,带有三个参数:
currentValue数组中正在处理的当前元素。
index可选数组中正在处理的当前元素的索引。
array可选调用数组映射。
因此,要在您的代码段中分解callback
函数中的三个参数:
this[i]
转换为map
回调的第一个参数,即currentValue。正如您所理解的那样,this
是调用map
的数组实例。所以this[i]
将引用数组的第i个索引中的值
i
是指数或当前指数。这是发送到callback
的for循环的迭代的第i个索引。
this
是对调用map
的数组本身的引用。
const arr = [1, 2, 3];
const callback = function(currentElement, index, array){
console.log(`The current element ${currentElement}`);
console.log(`The current index ${index}`);
console.log(`The array instance ${array}`);
return currentElement * 2; //multiplies each element with 2, this is the mapping operation
}
const mappedArray = arr.map(callback);
console.log(`The mapped array ${mappedArray}`);