奇怪的函数语法 [英] Weird function syntax

查看:50
本文介绍了奇怪的函数语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一个奇怪的函数,看起来像:

I saw a weird function that looked something like:

const x = (a) => (b) => a + b;

console.log(x(1)(2))

输出为3,我知道这是一个返回函数的函数,a和b都在同一范围内,但是我的问题是:

The output is 3, I understand that it's a function returning a function and both a and b are in the same scope but the questions I have are:

  1. 如何在现实生活中使用它?
  2. 不使用带有2个参数的函数,而改用它(对于单行函数)有什么好处?

推荐答案

通过此关闭,您可以获得具有恒定值的函数供以后添加.

With this closure, you could get a function with a constant value for later adding.

  1. 如何在现实生活中使用它?

您可以将返回的函数用于数组的映射.

You could take the returned function for a mapping of an array.

  1. 不使用带有2个参数的函数,而改用它(对于单行函数)有什么好处?

这是一种更干净实用的方法.

It's a cleaner and functional approach.

const
    x = a => b => a + b,
    add5 = x(5);

console.log([1, 2, 3].map(add5));

这篇关于奇怪的函数语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆