什么时候应该在 ES6 箭头函数中使用 return 语句 [英] When should I use a return statement in ES6 arrow functions
本文介绍了什么时候应该在 ES6 箭头函数中使用 return 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
新的 ES6 箭头函数说return
在某些情况下是隐式的:
The new ES6 arrow functions say return
is implicit under some circumstances:
该表达式也是该函数的隐式返回值.
The expression is also the implicit return value of that function.
在什么情况下我需要将 return
与 ES6 箭头函数一起使用?
In what cases do I need to use return
with ES6 arrow functions?
推荐答案
Jackson 在类似问题中部分回答了这个:
Jackson has partially answered this in a similar question:
隐式返回,但前提是没有阻塞.
Implicit return, but only if there is no block.
- 当一行扩展为多行并且程序员忘记添加
return
时,这将导致错误. - 隐式返回在语法上不明确.<代码>(名称)=>{id: name} 返回对象
{id: name}
... 对吗?错误的.它返回undefined
.这些大括号是一个显式块.id:
是一个标签.
- 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.
我会添加一个块的定义:
块语句(或其他语言的复合语句)用于组合零个或多个语句.该块由一对大括号分隔.
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.
示例:
// 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')
这篇关于什么时候应该在 ES6 箭头函数中使用 return 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文