Tell us what’s happening:
Doesn’t the map function just make a copy of the original array? If yes, then doesn’t this perform that function appropriately?
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 < s.length; i++){
newArray.push(s[i]);
}
// Only change code above this line
return newArray;
};
var new_s = s.myMap(function(item){
return item * 2;
});
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36.
you have a function passed as argument of the myMap method: that function is made so that it takes an element from the original array and returns the element to add to the new array
right now you are just pushing the elements to the newArray, you need to change something to instead push the new elements
i couldn’t figure it out on my own. I had to look up the solution. Can you explain to me why they use this.length? Does that just call upon any input that callback happens to be? Why not just use the variable callback and say callback.legnth? and how come you have to use callback(this[i]))?? I’m very confused.
for (let i = 0; i < this.length; i++) {
newArray.push(callback(this[i]));
}
when you iterate over an array with a for loop you use the iterating variable (in this case i ) that goes from 0 to the length of the array - it is a normal for loop to iterate over an array
you use this to refer to the array on which the method is being used
callback is the function used to change the array elements, so if this[i] is the old array element, callback(this[i]) returns the value you want the new array element to have