小编典典

JavaScript何时应在es6箭头函数中使用“ return”?

javascript

新的es6箭头功能说return在某些情况下是隐式的:

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

在什么情况下需要使用returnes6箭头功能?


阅读 667

收藏
2020-04-23

共1个答案

小编典典

隐式返回,但仅当没有块时才返回。
* 当单线扩展到多行并且程序员忘记添加时,这将导致错误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')
2020-04-23