ES6箭头函数的return语句中括号内的括号有什么作用? [英] What do parenthesis surrounding brackets in the return statement of an ES6 arrow function do?

查看:109
本文介绍了ES6箭头函数的return语句中括号内的括号有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如在redux动作中,我已经在某人的代码中看到过:

For example in redux actions, I've seen in someone's code:

export const updateMessage = text => {
   return (dispatch) => {
     dispatch(updateChatMessage(text))
   }
}

和:

const updateChatMessage = text => ({
   type: types.someActionType,
   text
})

它似乎是一个隐含的 return 功能,但我认为在粗箭头之后的箭头功能括号中已经暗示了该功能.

it seems to function as an imply a return but I thought that was already implied in an arrow functions brackets following the fat arrow.

括号({...})的作用是什么?他们有必要吗?是否有另一种方法可以完成同一件事?

What do the parenthesis ({...}) do? are they necessary? Is there an alternate way to accomplish the same thing?

推荐答案

当您编写 myFunction = value =>时,({prop:value})它返回对象 {prop:value} ,在这种情况下, {} 是对象定界符,而不是函数定界符"

when you write myFunction = value => ({prop: value}) it return the object {prop: value}, in this case {} are object delimiter and not 'function delimiter'

const updateChatMessage = text => ({
   type: types.someActionType,
   text
})

另一个,例如:

当您想将数组的每个元素乘以2时,您可以编写:

when you want to multiply by two each elem of an array you can write :

array.map(elem => {return elem * 2})

array.map(elem => elem * 2)//相同的结果

,如果您想要一个带有()的对象,例如包裹对象的对象:

and if you want an eg with () that wrap an object litteral :

let array = [{val: 2},
             {val: 4},
             {val: 8},
             {val: 16}];
             
let output = array.map( ({val}) => ({val: val*2}) );

console.log(output);

这篇关于ES6箭头函数的return语句中括号内的括号有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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