什么时候应该在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
时,这将导致错误. - 隐性收益在句法上是模棱两可的.
(name) => {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屋!
查看全文