函数式编程:在 PrototypePassed 上实现地图 JavaScript

Functional Programming: Implement map on a PrototypePassed JavaScript

我正在做 FreeCodeCamp 的练习,但我不明白其中的逻辑和代码。在这里:

// the global Array
var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback) {
  var newArray = [];
  // Add your code below this line
  this.forEach(a => newArray.push(callback(a)));
  // Add your code above this line
  return newArray;
};

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

谁能帮我解释一下?谢谢!

此代码将输出到 new_s 一个包含 s x 2

值的数组

让我们回顾一下:

Array.prototype.myMap = function(callback) { ... }
  • myMap是作用于数组的函数(Array.prototype)
  • 此函数有一个名为 callback 的参数。这个参数将是一个函数(即使在这里你仍然只能从参数的名称中猜测;)
  var newArray = [];
  // Add your code below this line
  this.forEach(a => newArray.push(callback(a)));
  // Add your code above this line
  return newArray;
  • 遍历 this 的所有值(您将应用 myMap 的数组)
  • callback引用的函数应用于每个值
  • callback函数的结果添加到newArray数组
  • Return 结果数组

最后:

var new_s = s.myMap(function(item) {
  return item * 2;
});
  • myMap 函数应用于 scallback 函数将 return 应用于 s 的函数,2 * s