我正在使用解构来声明一些像这样的变量:
const { a, b, c } = require('./something'),
{ e = 'default', f = 'default'} = c;
有没有办法让它变成单行? 我尝试过类似的东西:
const { a, b, c = { e = 'default', f = 'default'} } = require('./something');
但它给了我一个错误:
SyntaxError:无效的简写属性初始值设定项
答案 0 :(得分:10)
只需将=
替换为:
:
const {a, b, c: {e = 'default', f = 'default'}} = require('./something')
演示:
const { a, b, c: { e = 'default', f = 'default'} } = {a: 1, b: 2, c: {e: 3}}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)

打印:
a: 1, b: 2, e: 3, f: default
答案 1 :(得分:6)
如果对象中没有c
,则上述代码无效
const { a, b, c: { e = 'default', f = 'default'}} = {a: 1, b: 2}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)
const { a, b, c: { e = 'default', f = 'default'} ={} } = {a: 1, b: 2}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)
答案 2 :(得分:1)
该示例可以帮助您了解具有后备值的array
和object
的破坏
const person = {
firstName: 'Nikhil',
address: {
city: 'Dhule',
state: 'MH'
},
/*children: [
{
name: 'Ninu',
age: 3
}
]*/
}
const {
firstName,
address: {
city,
state
},
children: { 0: { name='Oshin' }={} }=[]
} = person;
console.log(`${firstName} is from ${city} and his first child name is ${name}`);