我可以在一行中解构嵌套变量并仍然处理未定义的值吗?
Can I destructure nested variables in one line and still cope with undefined values?
我有一个变量,我想解构它
const myFunc = ({name}) => {
console.log(name)
}
myFunc({name: 'hey'})
但是如果变量不存在怎么办?
const myFunc = ({name}) => {
console.log(name)
}
myFunc({name2: 'hey'})
它只是说 undefined
,很好
但是如果我要解构更多怎么办?
const myFunc = ({name, structure: {type}}) => {
console.log(name)
console.log(type)
}
myFunc({name: 'hey', structure : {type: 'hay'}})
好的,但是如果参数不存在怎么办?
const myFunc = ({name, structure: {type}}) => {
console.log(name)
console.log(type)
}
myFunc({name2: 'hey', structure2 : {type: 'hay'}})
然后它给出了一个(预期的)错误
问题是,我如何在同一个句子中解构时处理这些情况?还是我被迫分两步解构?
已解决:
问题与
重复
但是,如果只看这个特定问题,这个可能会有用
const myFunc = ({name, structure: {type} = {}}) => {
console.log(name)
console.log(type)
}
myFunc({name2: 'hey', structure2 : {type: 'hay'}})
我有一个变量,我想解构它
const myFunc = ({name}) => {
console.log(name)
}
myFunc({name: 'hey'})
但是如果变量不存在怎么办?
const myFunc = ({name}) => {
console.log(name)
}
myFunc({name2: 'hey'})
它只是说 undefined
,很好
但是如果我要解构更多怎么办?
const myFunc = ({name, structure: {type}}) => {
console.log(name)
console.log(type)
}
myFunc({name: 'hey', structure : {type: 'hay'}})
好的,但是如果参数不存在怎么办?
const myFunc = ({name, structure: {type}}) => {
console.log(name)
console.log(type)
}
myFunc({name2: 'hey', structure2 : {type: 'hay'}})
然后它给出了一个(预期的)错误
问题是,我如何在同一个句子中解构时处理这些情况?还是我被迫分两步解构?
已解决:
问题与
但是,如果只看这个特定问题,这个可能会有用
const myFunc = ({name, structure: {type} = {}}) => {
console.log(name)
console.log(type)
}
myFunc({name2: 'hey', structure2 : {type: 'hay'}})