如果其中一个参数包含多个值,如何使用柯里函数工作



我有一个高阶函数,虽然第一种情况multiply(4,5)按预期工作,但是否可以像multiply(2)(4, 5)一样传递多个参数。在这种情况下,答案是 8,但是是否可以以这样的方式创建一个柯里函数,以便它给出 40 作为结果

function multiply(s) {
  return function(b) {
    return s * b;
  }
}
console.log(multiply(4)(5))
console.log(multiply(2)(4, 5))

您可以使用 rest 参数...并收集两个函数上的所有参数并返回简化的结果。

function multiply(...a) {
    return function(...b) {
        return [...a, ...b].reduce((a, b) => a * b);
    };
}
console.log(multiply(4)(5));       //  20
console.log(multiply(2)(4, 5));    //  40
console.log(multiply(3, 2)(4, 5)); // 120

function multiply(s) {
  return function(b) {
    for(key in arguments)s*=arguments[key];
    return s;
  }
}
console.log(multiply(4)(5))
console.log(multiply(2)(4, 5))

我认为最好在您的情况下使用参数属性。

您可以使用

arguments执行以下操作:

function multiply(s) {
  return function () {
    return Array.from(arguments).reduce(function(accumulator, currentValue) {
      return accumulator * currentValue;
    }, s);
  }
}

如果您有一个或多个b参数,则可以这样做:

function multiply(s) {
  // Will contain the multiplication of all b arguments
  var result = 1;
  // ...b will return an the array arguments passed
  return function(...b) {
    // Loop through each of this array and update result
    for (var i = 0; i < b.length; i++) {
      result *= b[i];
    }
    // return the final result
    return s * result;
  }
}
console.log(multiply(4)(5))
console.log(multiply(2)(4, 5))

最新更新