nodejs arrow function with expression [duplicate]

落花浮王杯 提交于 2019-12-20 02:27:15

问题


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

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

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 ]

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


回答1:


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

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.

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 }).

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.



来源:https://stackoverflow.com/questions/34462795/nodejs-arrow-function-with-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!