什么时候应该在es6箭头函数中使用`return`? [英] When should I use `return` in es6 Arrow Functions?

查看:963
本文介绍了什么时候应该在es6箭头函数中使用`return`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的 es6箭头功能表示是隐式的:

The new es6 arrow functions say return is implicit under some circumstances:


表达式也是该函数的隐式返回值。 / p>

The expression is also the implicit return value of that function.

在什么情况下,需要使用返回与es6箭头函数? / p>

In what cases do I need to use return with es6 arrow functions?

推荐答案

杰克逊部分回答这个在类似的问题:

Jackson has partially answered this in a similar question:


隐式返回,但只有没有阻止。

Implicit return, but only if there is no block.


  • 当一个线程扩展到多行并且程序员忘记添加返回时,这将导致错误。 / li>
  • 隐式返回在语法上是模糊的。 (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 returns undefined. Those braces are an explicit block. id: is a label.

我会补充一下阻止的定义>:

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.

示例

// 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆