Home>

mapRealize with a function without using. .. .. I was talking about the problem,thisI didn't understand how to handle the object itself. I can't understand the answer code at all, so I'll ask you a question.

problem
var s = [23, 65, 98, 5];
Array.prototype.myMap = function (callback) {
  var newArray = [];
  // Only change code below this line
  // Only change code above this line
  return newArray;
};
var new_s = s.myMap (function (item) {
  return item * 2;
});
Corresponding source code
var s = [23, 65, 98, 5];
Array.prototype.myMap = function (callback) {
  var newArray = [];
  // Add your code below this line
  for (let 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;
});
Question
for (let i = 0;i<this.length;i ++) {


It is inthisso,var s = [23, 65, 98, 5];I know it points to an array of, but why

Array.prototype.myMap = function (callback) {


amongthisIs it possible to read the variable s with?
callback (this [i])but,newArray.push (callback (this [i]));Why specify callback

var new_s = s.myMap (function (item) {
  return item * 2;
});


Is it possible to execute the processing of?

  • Answer # 1

    why
    Array.prototype.myMap = function (callback) {
    Is it possible to read the variable s with this in?

    This in javascript is set automatically depending on how the function is called.
    hoge.fuga (~)When called in the form of, this in the fuga function is set to hoge.
    Of the problems.myMap (~)If so, s is set for this in the fuga function, so the variable s can be read with this.

    this --JavaScript | MDN

    It is callback (this [i]), but why specify callback in newArray.push (callback (this [i]));

    var new_s = s.myMap (function (item) {
    return item * 2;
    });

    Is it possible to execute the processing of?

    Simply think of a variable as having a function assigned to it.
    callbackPassed as an argument to the variablefunction (item) {return item * 2;}Because the function is assigned, for examplecallback (5)When you execute, the return value isTenWill be.

  • Answer # 2

    Array.prototype.myMap = function (callback) {

    ButArrayprototype,
    That is,Add a method to the array itselfBecause it's syntax.
    Sovar s = [23, 65, 98, 5];ofsBecause the variable is an array
    Of that array variablemyMapWhen you execute the method
    thisIssIt will point to the variable itself.

    However, in the present age, against the existing prototype,
    I feel that the syntax for prototyping pollution is not very good.
    (Personally)
    Well, if you need to make additional changes to an existing one, you can think of it.
    Even better, you can do the same with class syntax,
    (With more code maintenance)
    I feel like it's not a very good problem.
    Well, it's just my personal opinion, so I don't know.