具有多变量函数的 Lodash Map

Lodash Map with mulitvariable function

是否可以使用 lodash 遍历集合并将项目传递给需要两个(或更多)参数的函数?在下面的示例中,该函数应采用两个值并将它们相加。该地图应采用一个数组并向每个数组添加 10。以下是我认为这是如何工作的:

function x (a, b) {
    return a + b
}

var nums = [1, 2, 3]
console.log(_.map(nums,x(10)))
--->ans should be [11, 12, 13]
--->actually is [ undefined, undefined, undefined ]

你可以这样做:

var numbers = [1, 2, 3];

function x(value, number) {
    return value + number;
}

console.log(_.map(numbers, function(value) { return  x(value, 10) }));

当然,闭包很棒!只需创建一个 "closes"(包装)您的 x 函数并将 10 作为其第二个参数传递的函数。

function x (a, b) {
  return a + b;
}

function addTen (number) {
  return x(numberToAddTo, 10);
}

var nums = [1, 2, 3];

console.log(_.map(nums, addTen));

你在这里真正要做的是 "curry" x 函数,lodash 通过 curry() 支持它。柯里化函数是一次可以接受一个参数的函数:如果您不提供完整的参数集,它 returns 是一个需要剩余参数的函数。

这就是柯里化的样子:

function x(a,b) {
    return a + b;
}
x = _.curry(x);  //returns a curried version of x

x(3,5); //returns 8, same as the un-curried version

add10 = x(10);
add10(3); //returns 13

因此您的原始代码非常接近柯里化版本:

console.log(_.map([1,2,3], _.curry(x)(10))); //Prints [11,12,13]

(正如问题评论中指出的那样;Function.prototype.bind 也可用于柯里化,但如果您已经在使用 lodash,您不妨使用特定于该任务的东西)