Javascript 我什么时候应该在 es6 箭头函数中使用 `return`?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28889450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When should I use `return` in es6 Arrow Functions?
提问by Jess Telford
The new es6 arrow functionssay returnis implicit under some circumstances:
新ES6箭头功能,说return是在某些情况下隐含的:
The expression is also the implicit return value of that function.
该表达式也是该函数的隐式返回值。
In what cases do I need to use returnwith es6 arrow functions?
在什么情况下我需要使用returnes6 箭头函数?
回答by Jess Telford
Hymanson has partially answered thisin a similar question:
Hyman逊在一个类似的问题中部分回答了这个问题:
Implicit return, but only if there is no block.
- This will result in errors when a one-liner expands to multiple lines and the programmer forgets to add a
return.- Implicit return is syntactically ambiguous.
(name) => {id: name}returns the object{id: name}... right? Wrong. It returnsundefined. Those braces are an explicit block.id:is a label.
隐式返回,但前提是没有阻塞。
- 当一行扩展为多行并且程序员忘记添加
return.- 隐式返回在语法上是模棱两可的。
(name) => {id: name}返回对象{id: name}......对吗?错误的。它返回undefined。这些大括号是一个显式块。id:是一个标签。
I would add to this the definition of a block:
我会添加一个块的定义:
A block statement (or compound statement in other languages) is used to group zero or more statements. The block is delimited by a pair of curly brackets.
块语句(或其他语言的复合语句)用于组合零个或多个语句。该块由一对大括号分隔。
Examples:
例子:
// 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')
回答by Amarsh
I understand this rule-of-thumb ...
我理解这个经验法则......
For functions that are effectively transforms (one-line-manipulations of arguments), return is implicit.
对于有效转换的函数(参数的单行操作),返回是隐式的。
Candidates are:
候选人是:
// square-root
value => Math.sqrt(value)
// sum
(a,b) => a+b
For other operations (more than one-liners that require a block, return has to be explicit
对于其他操作(需要一个块的多个单行,返回必须是显式的
回答by Deci
There's another case here.
这里还有一个案例。
When writing a functional component in React, you can use parentheses to wrap implicitly returned JSX.
在 React 中编写函数式组件时,可以使用括号来包装隐式返回的 JSX。
const FunctionalComponent = () => (
<div>
<OtherComponent />
</div>
);
回答by Flavio Copes
Arrow functions allow you to have an implicit return: values are returned without having to use the returnkeyword.
箭头函数允许您隐式返回:无需使用return关键字即可返回值。
It works when there is a on-line statement in the function body:
当函数体中有在线语句时它起作用:
const myFunction = () => 'test'
console.log(myFunction()) //'test'
Another example, returning an object (remember to wrap the curly brackets in parentheses to avoid it being considered the wrapping function body brackets):
另一个例子,返回一个对象(记住将大括号包裹在括号中,以避免它被认为是包裹函数体括号):
const myFunction = () => ({value: 'test'})
console.log(myFunction()) //{value: 'test'}
回答by grayjohn
Here's another case that gave me some trouble.
这是另一个给我带来麻烦的案例。
// the "tricky" way
const wrap = (foo) => (bar) => {
if (foo === 'foo') return foo + ' ' + bar;
return 'nofoo ' + bar;
}
Here we define a function returning an anonymous function.The "tricky" bit is that the function body for the outer function (the part begining with (bar) => ...) visually looks like a "block", but it's not. Since it's not, implicit return kicks in.
这里我们定义了一个返回匿名函数的函数。“棘手”的一点是外部函数的函数体(以 (bar) => ... 开头的部分)在视觉上看起来像一个“块”,但它不是。既然不是,隐式返回就开始了。
Here's how wrap would execute:
以下是 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 way I unpacked this to make sure I understood it was to "unarrowify" the functions.
我打开它以确保我理解它的方式是“解开”功能。
Here's the semantic equivalent of the first code block, simply making the body of wrap() do an explicit return. This definition produces the same results as above. This is where the dots connect. Compare the first code block above with the one below, and it's clear that an arrow function itself is treated as an expression, not a block, and has the implied return.
这是第一个代码块的语义等价物,只是让 wrap() 的主体进行显式返回。此定义产生与上述相同的结果。这是点连接的地方。将上面的第一个代码块与下面的代码块进行比较,很明显箭头函数本身被视为表达式,而不是块,并且具有隐含的 return。
// the explicit return way
const wrap = (foo) => {
return (bar) => {
if (foo === 'foo') return foo + ' ' + bar;
return 'nofoo ' + bar;
}
}
The fully unarrowified version of wrap would be like this, which while not as compact as the fat arrowed up version, seems a lot easier to comprehend.
完全无箭头的 wrap 版本会是这样,虽然不像箭头向上的胖版本那么紧凑,但似乎更容易理解。
// the "no arrow functions" way
const wrap = function(foo) {
return function(bar) {
if (foo === 'foo') return foo + ' ' + bar;
return 'nofoo ' + bar;
};
};
In the end, for others that may have to read my code, and future me, I think I'd prefer to go the non arrow version which can be comprehended visually at first glance, rather than the arrow one which takes a fair bit of thought (and in my case experimentation) to grok.
最后,对于其他可能需要阅读我的代码的人,以及未来的我,我想我更愿意使用第一眼可以在视觉上理解的非箭头版本,而不是需要大量时间的箭头版本想(在我的情况下是实验)去理解。

