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

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

问题描述

我见过这样的 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:

( … ) => { … }

这将创建一个block如果您不想隐式返回表达式,并且如果您想进行中间计算或根本不返回值,则包含多个语句.例如:

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天全站免登陆