在javascript中的高阶函数中使用原型函数

在javascript中的高阶函数中使用原型函数

本文介绍了在javascript中的高阶函数中使用原型函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用reduce合并数组数组,我发现可以使用Array.prototype.concat函数,如下所示:

I'm trying to concat an array of arrays using reduce and I figured that I could use the Array.prototype.concat function like this:

烧入它的函数:

You can use bind to create a copy of a function with a particular this burned into it:

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

但是,现在已经清除,还有其他一些问题使您无法执行此操作。

However, now that that's cleared up, there are several other issues that stop you from doing this.

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

For one, reduce actually gets four arguments, including the current index and the whole array. You ignore these by having your (a,b)=> lambda only pass two of those four arguments into concat. That's fine, but when you supply a function directly as an argument to reduce, it will use all four arguments, so you'll get the result of the call Array.prototype.concat(a, b, currentIndex, arr).

此外,您正在做的不是明智地使用 Array.prototype 。 concat 函数连接其参数,并将其附加到 this 值的副本中。由于 Array.prototype 本身只是一个空数组(尽管具有许多其他数组用作继承属性的自有属性),所以这实际上与 []。concat(a,b)或(也许更可读) a.concat(b)。

Furthermore, what you're doing isn't a sensible use of Array.prototype. The concat function concatenates its arguments and appends them to a copy of the this value. Since Array.prototype is itself just an empty array (albeit with many own-properties that other arrays use as inherited properties), this is effectively the same as [].concat(a,b) or (perhaps even more readably) a.concat(b).

这篇关于在javascript中的高阶函数中使用原型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 08:23