首页 > 解决方案 > 像`map()`和`reduce()`这样的高阶函数如何接收它们的数据?

问题描述

我现在正在尝试编写自己的高阶函数,我想知道函数如何喜欢map()reduce()访问它们被应用到的数组。不仅适用于数组,还适用于任何高阶函数,如toString()or toLowerCase()

array.map()
^^^ // How do I get this data when I am writing my own higher order function?

array.myOwnFunction(/* data??? */)

我希望这是有道理的。我确定答案已经存在,但我很难知道要搜索什么来查找信息。

标签: javascript

解决方案


您可以将其添加到Array原型中,例如:

Array.prototype.myOwnFunction = function() {
  for (var i = 0; i < this.length; i++) {
    this[i] += 1;
  }

  return this;
};

const array = [1, 2, 3];

const result = array.myOwnFunction();

console.log(result);


推荐阅读