ES6 双箭头参数(即 const update = x => y => { } )

ES6 double arrow parameters (i.e. const update = x => y => { } )

下面代码中的双箭头参数是什么意思?

const update = x => y => {
   // Do something with x and y
}

与以下相比有何不同?

const update = (x, y) => {
   // Do something with x and y
}

谢谢!

让我们重写它们"old style",第一个是:

const update = function (x) {
  return function(y) {
    // Do something with x and y
  };
};

而第二个是:

const update = function (x, y) {
  // Do something with x and y
};

所以你可以看到它们是完全不同的,第一个 returns 是一个 "intermediate" 函数,而第二个是一个有两个参数的函数。

称为arrow functions,它是ES6提供的函数的新格式,在第一个例子中

const update = x => y => {
   // Do something with x and y
}

可以归结为

 var update = function (x){
        return function (y){
                 // Do something with x and y..
           }
    }

在 ES5 中,并且是 returns 函数的函数 与

完全不同
const update = function (x, y) {
  // Do something with x and y
};

语法 PARAM => EXPR 表示一个函数,它接受一个参数 PARAM 并且其主体是 { return EXPR; }。它本身就是一个表达式,所以可以作为其他函数的EXPR

x => y => { ... }

解析为

x => (y => { ... })

相同
x => { return y => { ... }; }

"double arrow parameters" 没有什么特别之处,这只是一个箭头函数返回另一个箭头函数,并且可以扩展为任意数量的参数。这是一种叫做 "currying".

的技术

来自Wikipedia

In mathematics and computer science, currying is the technique of translating the evaluation of a function that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions, each with a single argument.

这样做的好处是可以更轻松地部分应用和组合函数,这对于某些函数式编程风格很有用。

例子

假设您有一个函数 add,它接受两个数字并将它们相加,传统上您可以这样写:

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

现在假设您有一个数字数组,并希望将所有数字加 2。使用 map 和上面的函数,你可以这样做:

[1, 2, 3].map(x => add(2, x));

但是,如果该函数采用柯里化形式,则您无需将对 add 的调用包装在另一个箭头函数中即可使该函数适应 map 的预期。相反,您可以这样做:

const add = a => b => a + b;
[1, 2, 3].map(add(2));

这当然是一个微不足道且相当做作的示例,但它显示了它的本质。使部分应用函数变得更容易也使得编写可以组合在一起的小而灵活的函数变得更加实用,从而实现更多 "functional" 的编程风格。