后面带 () 的箭头函数是什么意思? [英] What does the arrow function with a () after means?

查看:23
本文介绍了后面带 () 的箭头函数是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const actionsMap = {
  [GET_USER]: (state, action) => ({ post: action.msg })
};

我有一段我偶然发现的代码.我一直在使用 {} 格式的箭头函数,这个 () 包装器是什么意思?

I have this code that I've stumbled upon. All the time I've been working with arrow functions I've seen on a {} format, what does this () wrapper mean?

推荐答案

使用箭头函数,您可以使用单个语句或块作为函数体.这两个是等价的:

With arrow functions, you can either use a single statement or a block as the function body. These two are equivalent:

() => foo
() => {
  return foo;
}

在您的示例中,如果 lambda 被定义为 () =>;{post: action.msg} 对象 ({}) 将被解释为主体块而不是对象.运行时会尝试将其解析为等效于:

In your example, if the lambda was defined as () => {post: action.msg} the object ({}) would be interpreted as a body block instead of an object. The runtime would try to parse it as an equivalent to:

function () {
  post: action.msg
}

这是一个命名标签和属性访问,在这里没有多大意义.通过包裹在括号中,您向解析器暗示它是一个要计算的表达式,并且单表达式主体上的粗箭头函数规则开始生效,使其等效于:

which is a named label and property access, and doesn't make much sense here. By wrapping in parens, you hint to the parser that it is an expression to be evaluated and the fat arrow function rules on single-expression bodies kick in, making it equivalent to:

function () {
  return {post: action.msg};
}

当你想做两个相关的事情时(偶尔在映射/归约算法中有用),为了解决单表达式规则,你可以使用括号对一对表达式进行分组:

To work around the single-expression rules when you want to do two related things (occasionally useful in map/reduce algorithms), you can use parens to group a pair of expressions:

foo.reduce((p, c) => (c.counted = true, p += c.value));

这将设置 ccounted 属性,然后将 c.value 添加到 p 并返回p += c.value 的结果作为 p 的新值.

This will set the counted property of c, before adding c.value to p and returning the result of p += c.value as the new value of p.

括号将 ECMAScript 中的表达式包装起来,可与逗号运算符一起使用,将多个表达式组合在一起.评估组时返回最后一个表达式的结果.

The parentheses wrap an expression in ECMAScript and can be used, with the comma operator, to group multiple expressions. The results of the last expression are returned when the group is evaluated.

例如:

var i = 0, j = 0;
console.log((j += 10, i += 2), j);

将打印 2 10,因为 j() 组中递增并稍后打印.

will print 2 10, since j is incremented in the () group and printed later.

这篇关于后面带 () 的箭头函数是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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