()=>之间的差异;和_ =>和(_)=>在JS ES6中 [英] Difference between ()=> and _=> and (_)=> in JS ES6
问题描述
我注意到,当我要编写粗箭头功能" => "时,我可以执行_=>
,()=>
或(_)=>
并且我的代码功能相同(至少对于我的用例而言)
I have notice that when I want to write a fat arrow function "=>" I can do _=>
, ()=>
or (_)=>
and my code functions the same (at least for my use cases)
它们之间是否有实际区别?如果是,我应该使用哪个?我大部分时间都在使用()=>
,但是有一天我使用_=>
看到了某人的代码,我认为它看起来很酷,所以我也开始使用它.
Is there an actual difference between them? If yes, which one should I use? I have been using ()=>
most of the time, but then one day I saw someone's code using _=>
and I thought it looked cool, so I started using it too.
我看到了这篇中篇文章 https://medium.freecodecamp.org/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26 作者声明可以使用_=>
或()=>
,但未指定是否存在差异.
I saw this medium article https://medium.freecodecamp.org/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26 where the author states you can use _=>
or ()=>
but doesn't specify if there's a difference.
推荐答案
胖箭头函数的一般形式是
The general form of a fat-arrow function is
(parameter-list) => function-body
如果没有任何参数,请使用一对空括号:
If you don't have any parameters, you use a pair of empty parentheses:
() => {}
如果只有一个参数,则为:
If you have a single parameter it's:
(x) => {}
由于_
是JavaScript中的有效标识符,因此您可以执行以下操作:
Since _
is a valid identifier in JavaScript, you can do:
(_) => {}
现在,有一条特殊的规则适用:如果只有一个参数 ,则可以跳过括号,这样您就可以得到:
Now, a special rule applies: If you have only one parameter, you can skip the parentheses, so you get:
_ => {}
请注意,这仅在您具有单个参数时才有效,即对于两个参数,您始终必须指定括号:
Please note that this is only valid if you have a single parameter, i.e. for two you always have to specify the parentheses:
(x, y) => {}
现在,在右侧,如果您的整个函数仅由带有return
的单个语句组成,例如
Now, on the right side, if your entire function only consists of a single statement with a return
, such as
x => { return x; }
您可以省略花括号和return
:
x => x
至少,如果在右侧不尝试返回对象(看起来像这样(此代码将无法工作!)),则为true:
At least, this is true if on the right side you don't try to return an object, which would look like this (this code won't work!):
x => { value: x }
之所以不起作用,是因为JavaScript无法将其与函数主体(也使用花括号)区分开来,因此现在您必须将其包装在括号中:
The reason why this does not work is that JavaScript can not distinguish this from a function body, which also uses curly braces, so now you have to wrap it in parentheses:
x => ({ value: x })
我认为关于胖箭头函数的语法,这几乎是您需要了解的所有内容.
I think that's pretty much everything you need to know about the syntax of fat arrow functions.
这篇关于()=>之间的差异;和_ =>和(_)=>在JS ES6中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!