Reputation: 167
I'm just a bit confused about how the this
keyword is used in this context. It is placed in an anonymous function with the parameter callback and is then used as such: callback(this[i], i, this)
. The exercise doesn't go into depth, but I understand that the this
is referring to the ar
object that is in the __proto__. Why are 3 arguments being placed in the anonymous function's parameter callback(this[i],i,this)
and how is it working under the hood? Any insight would be greatly appreciated, thank you.
Just to add to what was previously said, the exercise asked for me to implement my own version of 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()
Upvotes: 7
Views: 142
Reputation: 16908
The map
function will be called on an Array
instance, so in the following lines of code:
for(let i = 0; i < this.length; i++){
arr.push(callback(this[i], i , this))
}
is as per the signature of the callback function passed to the Array.prototype.map
method:
callback Function that produces an element of the new Array, taking three arguments:
currentValue The current element being processed in the array.
index Optional The index of the current element being processed in the array.
array Optional The array map was called upon.
So to breakdown the the three arguments in the callback
function in your snippet:
this[i]
translates to the first parameter of the map
callback, which is the currentValue. As you understood correctly this
is the array instance on which the map
is called. So this[i]
will refer to the value in the ith index of the array
i
is the index or current index. This is the ith index of the iteration of the for loop being sent to the callback
.
this
is an reference to the array itself on which the map
is invoked.
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}`);
Upvotes: 5