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

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

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

隐式返回,但仅当没有块时才返回。
* 当单线扩展到多行并且程序员忘记添加时,这将导致错误

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')


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5021850.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存