Javascript:回调中的无点样式

fmg*_*fmg 4 javascript functional-programming this pointfree

所以我希望数组的元素arr1也恰好属于数组arr2.我想arr1.filter(arr2.includes)应该做的伎俩,但它给了我一个错误(见下文).奇怪的是,arr1.filter(x => arr2.incudes(x))工作得很好.即使函数arr2.includesx => arr2.includes(x)引用不相等,它们不应该在相同的输入上采用相同的值吗?我错过了什么,这里?

> arr1 = ['a', 'b', 'c']
[ 'a', 'b', 'c' ]
> arr2 = ['a', 'c', 'd']
[ 'a', 'c', 'd' ]
>
> arr1.filter(x => arr2.includes(x))
[ 'a', 'c' ]
> arr1.filter(arr2.includes)
TypeError: Cannot convert undefined or null to object
    at includes (<anonymous>)
    at Array.filter (native)
    at repl:1:6
    ... etc ...
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 5

你不能做的原因有两个arr1.filter(arr2.includes):

  1. arr2.includes只是对函数的引用,但您需要的是对函数的引用以及要在(arr2)上使用它的数组.你可以通过使用来解决这个问题Function.prototype.bind,但是:

  2. filter传递其回调多个参数,而不只是一个:它传递值,索引和原始数组.includes将尝试使用它接收的第二个参数作为开始搜索filter的索引,因此当将索引传递给它时,它将使用它并跳过前导条目.

所以,通常的解决方法是使用知道它需要使用包装功能includesarr2,知道只有通过它的一个参数-这是你与你的箭头功能做了什么.

但是,请参阅MichałPerłakowski的答案,从功能编程角度使用实用程序函数创建回调函数而不是内联创建它.