使用无效合并或可选链接进行安全解构



目前我使用以下代码进行解构:

const myObj1 = {name: 'Abc'}
const {name} = myObj1
console.log(name)
const myObj2 = null
const {name2} = myObj2  // this will give error

现在,由于我们有可选的链接,我可以这样做:

const myObj = {name: 'Abc'}
const {name} = myObj
console.log(name) // 'Abc'
const myObj2 = null
const name2 = myObj2?.myObj2
console.log(name2) // undefined

有没有更好的方法或安全的方法使用空合并或可选链接进行解构?

>const name2 = myObj2?.myObj2- 这不是解构。

myObj2?.myObj2将返回您分配给name2undefined

你可以简单地做

const myObj2 = null;
const { name2 } = { ...myObj2 };
console.log(name2); // undefined

如果要使用空合并运算符,则应按如下所示使用它:

const myObj2 = null
const {name2} =  myObj2 ?? {};
console.log(name2) // undefined

如果 null 或未定义,null 合并运算符将在右侧返回操作数myObj2否则它将返回左侧的操作数,在您的情况下为myObj2

你正在做正确的事情,但它不是解构的,也不是真正有效的,当你想解构多个属性时,你可以这样做。

const myObj = {name: 'Abc', email: "test"}
const {name,email} = myObj
console.log(name, email) // 'Abc' "test"
const myObj1 = null
const {name1,email1} = myObj1 || {} // or myObj1 ?? {}
console.log(name1,email1) // undefined undefined

你可以试试||

const myObj2 = null;
const {name2, name3} = myObj2 || {}
console.log(name2, name3);
const myObj3 = {name4: "name4"};
const {name4, name5} = myObj3 || {}
console.log(name4, name5);

希望这有帮助。

最新更新