将对象文字括在箭头函数中的括号是什么意思? [英] What do the parentheses wrapping the object literal in an arrow function mean?

查看:237
本文介绍了将对象文字括在箭头函数中的括号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过这样的JavaScript代码:

I've seen JavaScript code such as this:

let a = () => ({ id: 'abc', name: 'xyz' })

在这种情况下,包裹对象的括号( … )指的是什么?是return的简写吗?

What do the parentheses ( … ) wrapping the object refer to in this instance? Is it a shorthand for return?

推荐答案

否.这些括号产生一个对象文字. 箭头函数具有多种语法,其中一种语法是:

No. Those parentheses produce an object literal. Arrow functions have many syntaxes, one of which is:

( … ) => expression

这将隐式返回一个表达式,例如:

This will implicitly return an expression, for example:

() => 1 + 1

此函数将隐式返回1 + 1,即2.另一个是这个:

This function will implicitly return 1 + 1, which is 2. Another one is this:

( … ) => { … }

这将创建阻止如果您不想隐式地返回一个表达式,并且想要进行中间计算或根本不返回任何值,则可以容纳多个语句.例如:

This will create a block to house multiple statements if you don't want to implicitly return an expression, and if you want to do intermediate calculations or not return a value at all. For example:

() => {
  const user = getUserFromDatabase();
  console.log(user.firstName, user.lastName);
}

当您要隐式返回对象文字时,就会出现问题.您不能使用( … ) => { … },因为它将被解释为一个块.解决的办法是使用括号.

The problem arises when you want to implicitly return an object literal. You can't use ( … ) => { … } because it'll be interpreted as a block. The solution is to use parentheses.

{ … }的括号是用来解释对象文字而不是块的.在分组操作符中,( … ),它们中只能存在表达式.块不是表达式,而是对象常量,因此假定对象常量.因此,与其创建一个块,不如使用以下语法:

The parentheses are there for the { … } to be interpreted an object literal, not a block. In the grouping operator, ( … ), only expressions can exist within them. Blocks are not expressions but object literals are, thus an object literal is assumed. Thus, instead of creating a block, it will use this syntax:

( … ) => expression

并隐式返回对象文字.如果没有括号,它将被解释为标签和字符串,而不是对象文字的键和值.

And implicitly return an object literal. Without the parentheses, it will be interpreted as labels and strings, not keys and values of an object literal.

let a = () => { 
  id: 'abc', //interpreted as label with string then comma operator
  name: 'xyz' // interpreted as label (throws syntax error)
}

此处的逗号将解释为逗号运算符,并且由于操作数必须是表达式,而标签是语句,因此将引发语法错误.

The comma here would be interpreted as the comma operator, and since the operands must be expressions, and labels are statements, it will throw a syntax error.

这篇关于将对象文字括在箭头函数中的括号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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