JS-在回调中,使用括号和 /或括号的区别是什么?
我目前正在使用React,我注意到该行为可能会根据如何使用回调而改变。 (不确定这是否称为 note法)。为了说明我的问题,让我们使用array.map()
。
Array.map(el=> return el.name);
Array.map((el)=> return el.name);
Array.map((el)=> {return el.name});
Array.map(el=> {return el.name});
这四种情况正确吗?他们每个人的预期行为是什么?是否可以始终“安全”使用任何可以使用 grammar 错误?
I'm currently using react and I have noticed that the behaviour may change depending on how a callback is used. (Not sure if this is called notation). To illustrate my question, let's use Array.map()
.
Array.map(el=> return el.name);
Array.map((el)=> return el.name);
Array.map((el)=> {return el.name});
Array.map(el=> {return el.name});
Are these four cases correct? What is the expected behaviour of each of them? Is there any that can be used "safely" always so it does bring up grammar errors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您省略(卷曲)括号时,无需写入返回,因为它会隐式返回右侧,当您使用括号时,您需要明确返回:
关于输入参数(左侧),当您有一个参数时,您可以留下它没有括号,但是有一个以上的参数意味着您在它们周围包括括号。如果您在编写打字稿时,即使使用一个参数,您也需要包含括号,因为您必须指定类型(当类型未隐式解析时)。
When you omit (curly)brackets then no need to write return because it will implicitly return right side, and when you use brackets then you need explicitly to return:
Regarding input parameters(left side), when you have one parameter you can leave it without brackets, but having more than one parameters implies you to include brackets around them. In case when you are writing typescript, even with one parameter you need to include brackets because you must specify type(when type is not implicitly resolved).