I don´t understand where does the this. key is coming from, so I can use a given array to supply to a callback function, why does the array is not stated in the parameters? can someone help?
Thanks
Your code so far
// The global variable
var s = [23, 65, 98, 5];
Array.prototype.myMap = function(callback){
var newArray = [];
// Only change code below this line
for(let i = 0; i < this.length; i++) {
let newItem = callback(this[i]);
newArray.push(newItem);
}
// Only change code above this line
return newArray;
};
var new_s = s.myMap(function(item){
return item * 2;
});
console.log(new_s);
As you can see, we don’t pass array to map either rather array is referred inside map function as this. The simplest form of thinking about this is “whatever comes to the left of period”.
Array.prototype.myMap = function(callback){
var newArray = ;
// Only change code below this line
for(let i = 0; i < this.length; i++) {
let newItem = callback(this[i]);
newArray.push(newItem);
}
// Only change code above this line
return newArray;
};
var new_s = s.myMap(function(item){
return item * 2;
});