为什么Array#map没有返回正确的数组? [英] Why doesn't Array#map return the correct array?

查看:138
本文介绍了为什么Array#map没有返回正确的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我写这样的东西时:

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

我希望收到类似 [{a:'hello'}的内容, {a:'hello'},{a:'hello'}] ,但它会返回 undefined 的列表。这是为什么?

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

推荐答案

对象被视为,因为箭头函数具有多种可接受的语法。它们包含一个包含多个语句的块:

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 }

实际上,您当前的代码被解释为带有 label 和字符串表达式,而不是对象字面值。因此,你的回调函数不会返回任何内容,你的数组将成为 undefined s的数组。

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' }));

这篇关于为什么Array#map没有返回正确的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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