我看到过这样的 JavaScript 代码:
let a = () => ({ id: 'abc', name: 'xyz' })
在这个例子中,将对象包裹在括号( … )
中是指什么?它是否是return
的简写?
在这个例子中,将对象包裹在括号( … )
中是指什么?它是否是return
的简写?
我看到过这样的 JavaScript 代码:
let a = () => ({ id: 'abc', name: 'xyz' })
在这个例子中,将对象包裹在括号( … )
中是指什么?它是否是return
的简写?
在这个例子中,将对象包裹在括号( … )
中是指什么?它是否是return
的简写?
( … ) => expression
() => 1 + 1
1 + 1
,也就是2
。另一个例子如下:( … ) => { … }
() => {
const user = getUserFromDatabase();
console.log(user.firstName, user.lastName);
}
( … ) => { … }
,因为它会被解释为一个块。解决方法是使用括号。{ … }
解释为对象字面量而存在的,而不是块。在分组运算符( … )
中,只有表达式可以存在于其中。块不是表达式,但对象字面量是,因此假定为对象字面量。因此,它将使用以下语法而不是创建块:( … ) => expression
隐式返回一个对象字面量。如果没有括号,它将被解释为labels和字符串,而不是对象字面量的键和值。
let a = () => {
id: 'abc', //interpreted as label with string then comma operator
name: 'xyz' // interpreted as label (throws syntax error)
}
它允许您创建一个表达式,因此
let a = () => ({ id: 'abc', name: 'xyz' })
指定a
在调用时返回封闭对象。
如果在此情况下删除()
,将会抛出一个错误,因为它不是有效的函数体语句,因为let a = () => { id: 'abc', name: 'xyz' }
中的{}
被解释为语句的边界,但内部内容在查看时无效。
let a = () => {
id: 'abc', /* Not valid JS syntax */
name: 'xyz'
}
let a = () => ({ id: 'abc', name: 'xyz' })
和 let a = () => {return ({ id: 'abc', name: 'xyz' })}
以及 let a = () => {return {id: 'abc', name: 'xyz' }}
是一样的,这种说法正确吗?” 答案是正确的,这三个表达式的结果相同,只是语法上略有不同。 - Mallory-Erik
{ id: 'abc', name: 'xyz' }
周围加上()
,将会抛出语法错误。({ id: 'abc', name: 'xyz' })
是一个表达式。 - guest271314