Why doesn't Array#map return the correct array

2020-03-31 08:27发布

When I write something like this:

var x = [1,2,3].map(x => { a : 'hello' });

I expect to receive something like [{a:'hello'},{a:'hello'},{a:'hello'}], but instead it returns a list of undefineds. Why is this?

enter image description here

4条回答
狗以群分
2楼-- · 2020-03-31 09:03

The "object" is treated as a block because arrow functions have multiple acceptable syntaxes. They includes a block which houses multiple statements:

param1 => { statements }
(param1, param2, …, paramN) => { statements }

In actuality your current code is interpreted as a block with a label and a string expression, not an object literal. Thus, your callback doesn't return anything and your array becomes an array of undefineds.

Wrap it in parentheses so that it is an expression and interpreted as an object literal (because blocks are not expressions, they are statements, and code inside grouping must be an expression):

var x = [1,2,3].map(x => ({ a : 'hello' }));
查看更多
何必那么认真
3楼-- · 2020-03-31 09:04

You need to put the returned object in parentheses:

var x = [1,2,3].map(x => ({ a : 'hello' }));

Otherwise, the code in curly braces it is treated as a body of a function.

查看更多
地球回转人心会变
4楼-- · 2020-03-31 09:06
var x = [1,2,3].map(x => ({ a : 'hello' }));
查看更多
神经病院院长
5楼-- · 2020-03-31 09:26

You need some parenthesis around the object, otherwise you get a block statement with a label.

To prevent the block statement in arrow functions, you need to use the grouping operator to get an expression as return value.

var x = [1, 2, 3].map(x => ({ a: 'hello' }));

console.log(x);

查看更多
登录 后发表回答