JavaScript:多个参数

时间:2018-05-15 22:27:31

标签: javascript function lambda currying

举例说明" currying"可能在JavaScript中使用:

const component = (argument1) => (argument2) => {
   // Do something
}

4 个答案:

答案 0 :(得分:2)

这称为函数currying。它对于实现装饰器模式很有用。

例如,我们假设我们从一个简单的函数add开始。



const add = (a, b) => a + b;

console.log(add(1, 2));




现在,让我们说我们想要添加两个数字,但每次都要加10个。

我们可以这样做:



const add = (a, b) => a + b + 10;

console.log(add(1, 2));




但是,我们失去了原来的功能。

所以我们使用函数currying来做到这两点:



// We keep the original add function
const add = (a, b) => a + b;

// And create another function that returns the modified function
const addTen = (addFunction) => (a, b) => 10 + addFunction(a, b);

// then we store the new function in a different variable
const addPlusTen = addTen(add);

// ...and call the returned function

console.log(add(1, 2));
console.log(addPlusTen(1, 2));

// This becomes useful when we need to make an addPlusFive, addPlusSix and addPlusSeven functions:

const addFive = (addFunction) => (a, b) => 5 + addFunction(a, b);
const addSix = (addFunction) => (a, b) => 6 + addFunction(a, b);
const addSeven = (addFunction) => (a, b) => 7 + addFunction(a, b);

const addPlusFive = addFive(add);
const addPlusSix = addSix(add);
const addPlusSeven = addSeven(add);

console.log(addPlusFive(1, 2));
console.log(addPlusSix(1, 2));
console.log(addPlusSeven(1, 2));




答案 1 :(得分:1)

在你的代码中有两个箭头函数,一个返回另一个,它可以帮助你使用Closure维护状态/范围

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

const multiplier = (argument1) => (argument2) => {
   return argument2 * argument1;
};

const multiples8 = multiplier(8);

console.log(multiples8(5));
console.log(multiples8(6));
console.log(multiples8(7));

答案 2 :(得分:1)

您正在做的事情称为链接。

const add = (a) => (b) => {
    return a + b;
}

var add5 = add(5); // returns partially applied function
var result = add5(4); // which can be invoked with its own parameter

console.log(result); // 9

箭头函数提供更清晰的语法,因为如果有一个参数可以省略参数周围的括号,并且如果函数体是单行,则可以省略方括号。我们可以使用常规的js函数语法编写相同的代码:

const add = function(a){
    return function(b){
    return a + b
  }
}

答案 3 :(得分:-1)

您的代码包含两个嵌套箭头函数的简短版本。以下是完整版本的外观(使用return语句和括号,它应该看起来更清晰):

let component = (argument1) => { 
   // console.log(argument1);
   return (argument2) => {
       // console.log(argument2);
   }
}

component('aa')('bb');

第一个函数(带参数1)返回FUNCTION。返回的函数接受参数2。