Jackson在类似的问题中已经进行了部分回答:链接
如果没有代码块,则为隐式返回。
- 当一行扩展到多行时,程序员忘记添加
return
会导致错误。- 隐式返回在语法上存在歧义。例如,
(name) => {id: name}
返回对象{id: name}
吗?错了。它返回undefined
。这些花括号是一个显式的代码块。id:
是一个标签。
我要补充一下代码块的定义:
代码块用于组合零个或多个语句。代码块由一对花括号括起来。
示例:
// 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')
我理解这个经验法则...
对于那些实际上是转换(将参数进行一行操作)的函数,返回值是隐含的。
候选项为:
// square-root
value => Math.sqrt(value)
// sum
(a,b) => a+b
对于其他需要使用代码块的操作(不只是一行代码), 必须显式地使用 return 语句。
这里还有另一个例子。
例如,在编写 React 中的功能组件时,您可以使用括号来包装隐式返回的 JSX。
const FunctionalComponent = () => (
<div>
<OtherComponent />
</div>
);
这是另一个让我感到困扰的案例。
// the "tricky" way
const wrap = (foo) => (bar) => {
if (foo === 'foo') return foo + ' ' + bar;
return 'nofoo ' + bar;
}
这里我们定义了一个返回匿名函数的函数。"棘手"的部分在于外部函数的函数体(以(bar) => ...开头的部分)在视觉上看起来像一个"块",但实际上不是。由于它不是块,隐式返回就会发生。
下面是wrap函数的执行过程:
// use wrap() to create a function withfoo()
const withfoo = wrap('foo');
// returns: foo bar
console.log(withfoo('bar'));
// use wrap() to create a function withoutfoo()
const withoutfoo = wrap('bar');
// returns: nofoo bar
console.log(withoutfoo('bar'));
// the explicit return way
const wrap = (foo) => {
return (bar) => {
if (foo === 'foo') return foo + ' ' + bar;
return 'nofoo ' + bar;
}
}
// the "no arrow functions" way
const wrap = function(foo) {
return function(bar) {
if (foo === 'foo') return foo + ' ' + bar;
return 'nofoo ' + bar;
};
};
return
关键字就能返回值。const myFunction = () => 'test'
console.log(myFunction()) //'test'
const myFunction = () => ({value: 'test'})
console.log(myFunction()) //{value: 'test'}
如果符合以下条件,从箭头函数中省略大括号 {} 和 return 关键字是可以的: (1) 在 return 语句之前没有任何代码(例如赋值语句); (2) 返回的是单一实体 [注:单一实体可以是多行。如果是这样,那么你只需要使用普通的括号(),就像下面的例子一样:
posts.map(post => (
<li key={post.id}>
{post.title}
</li>
))
name
的箭头函数,该函数用括号括起来,并使用一个参数“Jess”调用。每种情况下在=>
和)('Jess')
之间的代码都是箭头函数的主体。可以将其视为形式为(function (name) { return { id: name } })('Jess')
的立即执行函数表达式的简写形式。 - Russ Cam