ES6 箭头函数的 return 语句中的圆括号有什么作用?
What do parenthesis surrounding brackets in the return statement of an ES6 arrow function do?
例如在redux actions中,我在某人的代码中看到:
export const updateMessage = text => {
return (dispatch) => {
dispatch(updateChatMessage(text))
}
}
和:
const updateChatMessage = text => ({
type: types.someActionType,
text
})
它似乎起到了暗示作用 return
但我认为这已经暗示在粗箭头后面的箭头函数括号中。
圆括号({...})
有什么作用?他们有必要吗?有没有其他方法可以完成同样的事情?
当你写 myFunction = value => ({prop: value})
它 return 对象 {prop: value}
,在这种情况下 {}
是对象定界符而不是 'function delimiter'
const updateChatMessage = text => ({
type: types.someActionType,
text
})
另一个例子:
当你想将数组的每个元素乘以二时,你可以这样写:
array.map(elem => {return elem * 2})
或
array.map(elem => elem * 2)
//同样的结果
如果你想要一个带有 ()
的 eg 来包装一个对象:
let array = [{val: 2},
{val: 4},
{val: 8},
{val: 16}];
let output = array.map( ({val}) => ({val: val*2}) );
console.log(output);
如果你用圆括号括起方括号,你就是在使你的函数 return 成为一个对象文字(因此你不需要 return 关键字)。如果您不使用括号,则必须使用 return 关键字。
在第一个示例中,{}
用于标识多行代码,这就是为什么需要 return 才能获得 undefined
以外的内容的原因。
在第二个例子中,{}
用于创建对象。
// Parenthesize the body of a function to return an object literal expression:
params => ({foo: bar})
这意味着如果您想 return 隐式地使用一个对象,您必须将其括在括号中。
没有这个,大括号内的代码将被视为函数体而不是对象(如您所愿)
以下是等价的:
params => { return {foo: bar}} // Explicitly return an object (from function body)
params => ({foo: bar}) // Implicitly return an object by wrapping it with parentheses
例如在redux actions中,我在某人的代码中看到:
export const updateMessage = text => {
return (dispatch) => {
dispatch(updateChatMessage(text))
}
}
和:
const updateChatMessage = text => ({
type: types.someActionType,
text
})
它似乎起到了暗示作用 return
但我认为这已经暗示在粗箭头后面的箭头函数括号中。
圆括号({...})
有什么作用?他们有必要吗?有没有其他方法可以完成同样的事情?
当你写 myFunction = value => ({prop: value})
它 return 对象 {prop: value}
,在这种情况下 {}
是对象定界符而不是 'function delimiter'
const updateChatMessage = text => ({
type: types.someActionType,
text
})
另一个例子:
当你想将数组的每个元素乘以二时,你可以这样写:
array.map(elem => {return elem * 2})
或
array.map(elem => elem * 2)
//同样的结果
如果你想要一个带有 ()
的 eg 来包装一个对象:
let array = [{val: 2},
{val: 4},
{val: 8},
{val: 16}];
let output = array.map( ({val}) => ({val: val*2}) );
console.log(output);
如果你用圆括号括起方括号,你就是在使你的函数 return 成为一个对象文字(因此你不需要 return 关键字)。如果您不使用括号,则必须使用 return 关键字。
在第一个示例中,{}
用于标识多行代码,这就是为什么需要 return 才能获得 undefined
以外的内容的原因。
在第二个例子中,{}
用于创建对象。
// Parenthesize the body of a function to return an object literal expression:
params => ({foo: bar})
这意味着如果您想 return 隐式地使用一个对象,您必须将其括在括号中。
没有这个,大括号内的代码将被视为函数体而不是对象(如您所愿)
以下是等价的:
params => { return {foo: bar}} // Explicitly return an object (from function body)
params => ({foo: bar}) // Implicitly return an object by wrapping it with parentheses