admin管理员组

文章数量:1287935

Is it possible to use lodash to iterate over a collection and pass the item to a function that requires two (or more) arguments? In the following example, the function should take two values and add them. The map should take an array and add 10 to each. The following is how I thought this worked:

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 ]

Is it possible to use lodash to iterate over a collection and pass the item to a function that requires two (or more) arguments? In the following example, the function should take two values and add them. The map should take an array and add 10 to each. The following is how I thought this worked:

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 ]
Share Improve this question asked May 17, 2015 at 14:30 TerryTerry 7851 gold badge8 silver badges20 bronze badges 1
  • 2 Partial application, _.map(nums, x.bind(null, 10)), or curry x. – elclanrs Commented May 17, 2015 at 14:36
Add a ment  | 

3 Answers 3

Reset to default 7

What you're essentially trying to do here is "curry" the x function, which lodash supports via curry(). A curried function is one that can take its arguments one at a time: if you don't provide a full set of arguments, it returns a function expecting the remaining arguments.

This is what currying looks like:

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

So your original code is very close to the curried version:

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

(As was pointed out in the ment on the question; Function.prototype.bind can also be used for currying, but if you're already using lodash, you might as well use something specific to the task)

You can do it like this:

var numbers = [1, 2, 3];

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

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

Sure, closure is awesome! Just make a function that "closes" (wraps) your x function and passes 10 as its second argument.

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

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

var nums = [1, 2, 3];

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

本文标签: javascriptLodash Map with mulitvariable functionStack Overflow