具有表达式的nodejs箭头函数 [英] nodejs arrow function with expression

查看:142
本文介绍了具有表达式的nodejs箭头函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档,您可以返回来自箭头函数的表达式:

According to the documentation, you can return an expression from an arrow function:

(param1, param2, …, paramN) => expression
     // equivalent to:  => { return expression; }

但这似乎没有像我所期望的那样工作(nodejs 4.2.3) p>

but this doesn't seem to work as I would expect (nodejs 4.2.3)

> [1,2,3].map(i => i);
[ 1, 2, 3 ]
> [1,2,3].map(i => {});
[ undefined, undefined, undefined ]

不应该第二个例子返回3个空对象?或者我错过了一些东西?

Shouldn't the 2nd example return 3 empty objects? Or am I missing something?

推荐答案

根据文档,胖箭头功能的正文可以写成单个表达式或一系列语句包装到 {} (正如你编写的旧函数体)。

According to the docs, the body of fat arrow function can be written as either a single expression or a series of statements wrapped into {} (just as you write bodies of plain old functions).

关键是,如果解析器遇到 => 之后的中,它与第二个选项一起出现。现在,在第一次编辑此答案时是否使用空对象文字或全对象文字(例如 {a:2} )并不重要)被视为对象文字,仅作为函数的正文。

The point is, if parser encounters { after the =>, it goes with the second option. Now, it doesn't matter whether or not you use empty object literal or full object literal (like { a: 2 } in the first edit of this answer) - it's never treated as object literal, only as a function's body.

如果函数没有返回声明? Right - 此函数返回 undefined 。这就是为什么你得到其中的三个结果为 map (两者用于 => {} => {a:2} )。

And what happens if function doesn't have a return statement? Right - this function returns undefined. That's why you get three of those as result of map (both for => {} and for => { a: 2 }).

要获取三个空对象,只需将 {} into (),如下所示:

To get three empty objects instead, just wrap {} into (), like this:

[1,2,3].map(i => ({}));

...因为它强制解析器与表达式路径。

... as it forces the parser to go with expression path.

这篇关于具有表达式的nodejs箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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