花括号在array.map()中的含义 [英] Meaning of curly braces in array.map()

查看:45
本文介绍了花括号在array.map()中的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .map()函数,用于更改 data 数组中对象的 isActive 属性值.但是用花括号将其包装返回未定义,而用括号将其包装或不进行包装将返回更新后的值.圆括号在箭头功能中用作包装器,但是.map()的工作原理是否有所不同?

I have a .map() function that changes isActive property value of objects in data array. However wraps it with curly braces returns me undefined whereas wrapping it with parenthesis or no wrap returns the updated value. Curly braces are used as a wrapper in an arrow function but does it work differently for .map()?

    const newData = data.map((data) => {
      data.label === label ? { ...data, isActive: !data.isActive } : data,
    });
    console.log(newData) 
    //undefined



    const newData = data.map((data) => 
      data.label === label ? { ...data, isActive: !data.isActive } : data,
    );
    console.log(newData) 
    //returns updated newData

推荐答案

这是箭头功能的行为.箭头函数的语法设计简洁.

That’s the behavior of arrow function. Arrow function syntax is designed to be terse.

(arg) => [single expression]

如果箭头后面是一个不带花括号的单个表达式,则表示返回该表达式的值.省略 return 关键字.

If what follows the arrow is one single expression without curly braces, it implies returning the value of that expression. The return keyword is omitted.

如果用大括号括住大括号,则括号内的内容将被视为普通函数体,如果要返回值,则必须使用 return 关键字.

If wrapping curly braces follows the arrow, then what goes inside the braces are treated as normal function body, and return keyword must be used if you mean to return a value.

所以(x)=>x + 1 转换为:

function (x) {
  return x + 1;
}

(x)=>{x + 1} 被翻译为:

function (x) {
  x + 1;
}

我还必须添加(x)=>({x})被翻译为:

I must also add that (x) => ({ x }) is translated to:

function (x) {
  return { x: x };
}

大括号 {...} 可以表示对象文字,函数主体或代码块.

Curly brace {...} can mean an object literal, a function body or a code block.

为了消除歧义,您需要在括号两边加上括号,以告知解析器将 {...} 解释为对象文字表达式".

In order to disambiguate, you need to put parenthesis around the braces to tell the parser to interpret {...} as an "object literal expression".

这篇关于花括号在array.map()中的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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