javascript - 在 JavaScript 中使用高阶函数中的原型(prototype)函数

标签 javascript arrays node.js prototype higher-order-functions

我正在尝试使用reduce 连接数组,我想我可以使用 Array.prototype.concat 函数,如下所示:

arr = [[1],[2],[3]]
arr.reduce((a, b) => Array.prototype.concat(a, b), [])

效果很好,并给出了数组[1, 2, 3]。然后我想我可以更聪明,这样做:

arr = [[1],[2],[3]]
arr.reduce(Array.prototype.concat, [])

但这给了我一个错误:

TypeError: Array.prototype.concat called on null or undefined
    at Array.reduce (native)
    at Object.<anonymous> (/home/axel/Developer/temp/reduce2.js:2:5)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.runMain (module.js:590:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)

似乎认为Array.prototype.concat未定义。这是为什么?

最佳答案

concat作为某个对象的方法(即该方法执行的 this 值)。当您将函数传递给函数时,您不会传递任何 this值(value)。因此,您实际上正在做类似的事情:

var rawConcat = Array.prototype.concat;
rawConcat(a,b);

您可以使用bind创建具有特定 this 的函数的副本烧入其中:

arr.reduce(Array.prototype.concat.bind(Array.prototype), [])

但是,既然问题已解决,还有其他几个问题会阻止您执行此操作。

其中一个,reduce实际上获取四个参数,包括当前索引和整个数组。您可以通过 (a,b)=> 来忽略这些lambda 仅将这四个参数中的两个传递给 concat 。这很好,但是当您直接提供一个函数作为 reduce 的参数时,它将使用所有四个参数,因此您将获得调用 Array.prototype.concat(a, b, currentIndex, arr) 的结果.

此外,您所做的并不是 Array.prototype 的合理使用。 concat函数连接其参数并将它们附加到 this 的副本中值(value)。自 Array.prototype本身只是一个空数组(尽管有许多其他数组用作继承属性的自有属性),这实际上与 [].concat(a,b) 相同或(也许更易读)a.concat(b) .

关于javascript - 在 JavaScript 中使用高阶函数中的原型(prototype)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42541207/

相关文章:

javascript - 如何禁用 Angular Material Stepper 中的步骤?

c - 如何在 C 中将整数拆分为单独的多位整数?

javascript - 调用函数并接收 JSON

javascript - D3.js 不工作的非常简单的教程示例

javascript - 正确的 React 方式来处理父组件中仅作用于选定子组件的函数?

javascript - 将 JSON 数组转换为单独的 JS 变量

node.js - NPM 模块不会在没有 sudo 的情况下全局安装

node.js - 安装 zmq Node 模块时出错

javascript - Passport-Google-OAuth 回调不起作用

asp.net - 自定义排序文件名字符串数组