简体   繁体   English

数组映射返回未定义的数组时应返回对象数组

[英]Array map returning array of undefined when should return array of objects

Why does 为什么

['a', 'b', 'c'].map((x) => { letter: x }) returns a array of undefined ['a', 'b', 'c'].map((x) => { letter: x })返回一个undefined数组

and

['a', 'b', 'c'].map((x) => [{ letter: x }][0]) returns a array of objects correctly? ['a', 'b', 'c'].map((x) => [{ letter: x }][0])正确返回一个对象数组?

You need to wrap object in () 你需要在()包装对象

 var result = ['a', 'b', 'c'].map((x) => ({ letter: x })) console.log(result) 

Because 因为

  • You use the curly brackets as block statement . 您使用大括号作为块语句

  • You have letter as a label . 你有letter作为标签

  • x is just a value without some action. x只是没有某些动作的值。

  • The return of undefined is the standard return value of a function without any return statement with value. undefined的返回值是函数的标准返回值,没有任何带语句的return语句。

    To return a value other than the default, a function must have a return statement that specifies the value to return. 要返回默认值以外的值,函数必须具有指定要返回的值的return语句。 A function without a return statement will return a default value. 没有return语句的函数将返回默认值。 In the case of a constructor called with the new keyword, the default value is the value of its this parameter. 对于使用new关键字调用的构造函数 ,默认值是其this参数的值。 For all other functions, the default return value is undefined. 对于所有其他函数,默认返回值未定义。

Correct call for mapping objects. 正确调用映射对象。

 console.log(['a', 'b', 'c'].map(x => ({ letter: x }))); 

A function that lacks an explicit return statement will return undefined. 缺少显式return语句的函数将返回undefined。 () => {} is equivalent to function(){} . () => {}等同于function(){} x => x is equivalent to function(x){ return x;} x => x相当于function(x){ return x;}

So arrow function without {} will return computed value of the expression. 因此,没有{}箭头函数将返回表达式的计算值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM