在对象的方法上调用每个下划线 (_.each)

Calling underscore each (_.each) on an object's method

我正在尝试使用 underscore.js each 函数将数组的每个元素就地推送到现有数组。

为此,我假设我可以使用 push 数组 方法 ,而不是通常的 匿名函数 通过到 each,前提是我将上下文对象作为第三个参数传递给 each:

> var a = [1,2,3]
> var b = []
> _.each(a, b.push, b)

我希望 b 现在是 [1,2,3],但实际上是:

Array [ 1, 0, Array[3], 2, 1, Array[3], 3, 2, Array[3] ]

这是怎么回事?

_.each 在许多其他函数式编程语言或库中的工作方式与 foreach 不同。如 documentation

中所述

Each invocation of iteratee is called with three arguments: (element, index, list)

如果您改用 console 方法,您会看到:

> _.each(a, console.log, console)

  1 0 Array [ 1, 2, 3 ]
  2 1 Array [ 1, 2, 3 ]
  3 2 Array [ 1, 2, 3 ]

所以 push 最终接受了这九个值,而不是可能希望的三个值。可以只使用匿名函数:

_.each(a, function(x) { b.push(x) })

然后 b 就是预期的 [1,2,3]

或者,在这种特殊情况下,使用其他方法之一 extend an array in JavaScript