Implement a Map prototype with for loop

Implement a Map prototype with for loop
0

#1

@RandellDawson
Sir I want to ask,

Array.prototype.myMap = function(callback){
  var newArray = [];
  // Add your code below this line
  newArray = Object(this);
  for(let i = 0; i < newArray.length; i++){
    newArray[i] = callback(newArray[i]);
  }
  // Add your code above this line
  return newArray;

};

in line newarray = Object(this); didn’t it point to the global window array object and not on this object? please explain it to me why is it working?


"Implement a Map prototype" with forEach?
#2

Read this:

Passing “this” to Object essentially creates an Array object

Ps. I would not add this line of code since the newArray is already an array object by definition.


#3

I moved your question to a new thread, because the question you asking and your solution is different than the OP of the thread you replied to. It is typically better if you have your own topic for a different question and especially if you are not answering the OP’s original question.

In your code, this refers to the instance of the Array() Object. Writing Object(this) and assigning to newArray now allows your function to mutate the original array elements. That is NOT what you want to do. The bulit-in map method returns a new array. Stick with the original initialization of newArray shown in the original code (seen below), then you can reference this inside your anonymous function and access the original array’s elements.

var newArray = [];

#4

ok sir I understand that this in this context points to the original array and if we use it, it’s gonna change the original array.
But if we write like this as pointed out by @msmith1114 solution
Array.prototype.myMap = function(callback){
var newArray = [];
// Add your code below this line
for(var i = 0;i < this.length;i++)
{
newArray.push(callback(this[i]));
}
// Add your code above this line
return newArray;

};

var new_s = s.myMap(function(item){
return item * 2;
});
Didn’t the callback function is a method in newArray.push(callback(this[i])) that uses the this object and shouldn’t we have to modify how we execute the callback function to preserve the this object context? Or else the this object will either point to the global window object , if callback was passed to a global function ?


#5

No, No, and No. this refers to the object (array in this case) the method is called upon.


#6

thank you sir I have been told by someone that I have to use some(I don’t know about them) call and apply functions to that callback function of javascript and my code is incorrect for the same reason.


#7

If your code is still the same as you posted at the top here, I have already explained why it will not work.