我正在尝试使用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/