发布于 2015-03-06 06:56:42
杰克逊在一个类似的问题中有部分answered this:
隐式返回,但仅当没有块时才返回。
当一行代码扩展为多行,并且程序员忘记添加return
.
(name) => {id: name}
返回对象{id: name}
...对吗?不对。它返回undefined
。这些大括号是显式的块。id:
是一个标签。我将在此添加block的定义
块语句(或其他语言中的复合语句)用于对零个或多个语句进行分组。该块由一对大括号分隔。
示例:
// returns: undefined
// explanation: an empty block with an implicit return
((name) => {})()
// returns: 'Hi Jess'
// explanation: no block means implicit return
((name) => 'Hi ' + name)('Jess')
// returns: undefined
// explanation: explicit return required inside block, but is missing.
((name) => {'Hi ' + name})('Jess')
// returns: 'Hi Jess'
// explanation: explicit return in block exists
((name) => {return 'Hi ' + name})('Jess')
// returns: undefined
// explanation: a block containing a single label. No explicit return.
// more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
((name) => {id: name})('Jess')
// returns: {id: 'Jess'}
// explanation: implicit return of expression ( ) which evaluates to an object
((name) => ({id: name}))('Jess')
// returns: {id: 'Jess'}
// explanation: explicit return inside block returns object
((name) => {return {id: name}})('Jess')
发布于 2017-01-12 07:43:23
我明白这条经验法则...
对于有效转换的函数(参数的一行操作),返回是隐式的。
候选对象包括:
// square-root
value => Math.sqrt(value)
// sum
(a,b) => a+b
对于其他操作(需要块的多个一行程序,返回必须是显式的
发布于 2018-07-06 17:46:20
这里还有另一个案例。
在React中编写函数组件时,可以使用括号包装隐式返回的JSX。
const FunctionalComponent = () => (
<div>
<OtherComponent />
</div>
);
https://stackoverflow.com/questions/28889450
复制相似问题