gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:59:14 25 4
gpt4 key购买 nike

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

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将返回 undefined您分配给 name2 .
你可以简单地做

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

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

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

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

关于javascript - 使用无效合并或可选链接进行安全解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62727568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com