带括号或括号的箭头功能之间的区别 [英] difference between arrow functions with parentheses or brackets

查看:77
本文介绍了带括号或括号的箭头功能之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个在javascript中有什么区别?在脚本编写中是什么意思?

What's the difference between these two in javascript? what does it mean in scripting?

const Test1 = () => {
    console.log('test1')
}


const Test2 = () => (
    console.log('test2')
)

推荐答案

基本"形式带有花括号,就像常规函数一样:

The "basic" form is with curly braces, just like regular functions:

() => {
    ...
}

但是,箭头功能允许一种特殊情况下的速记:

However, arrow functions allow one special case shorthand:

() => plain expression

如果不使用花括号,则可以改用一个普通表达式,带有隐式的 return .这两个是等效的:

If you don't use curly braces, you may use one plain expression instead, with an implicit return. I.e. these two are equivalent:

() => { return 42; }
() => 42

因此,使用括号的版本将作为单个表达式的版本,并且将返回 console.log 的返回值(尽管这是 undefined ),但是不会在使用花括号的版本上显示.

So your version using parentheses counts as the single expression version and the return value of console.log will be returned (which is undefined either way though), whereas it won't on the version using curly braces.

这篇关于带括号或括号的箭头功能之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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