gpt4 book ai didi

javascript - 安全地访问 Javascript 嵌套对象

转载 作者:IT老高 更新时间:2023-10-28 23:07:42 25 4
gpt4 key购买 nike

我有基于 json 的数据结构,其中的对象包含嵌套对象。为了访问特定的数据元素,我将对象属性的引用链接在一起。例如:

var a = b.c.d;

如果 b 或 b.c 未定义,这将失败并出现错误。但是,如果它存在,我想获得一个值,否则只是未定义。无需检查链中的每个值是否都存在的最佳方法是什么?

我希望尽可能保持这种方法的通用性,这样我就不必添加大量的辅助方法,例如:

var a = b.getD();

var a = helpers.getDFromB(b);

我还想尽量避免使用 try/catch 构造,因为这不是错误,因此使用 try/catch 似乎是错误的。这合理吗?

有什么想法吗?

最佳答案

ECMAScript2020 ,并且在 Node v14 中,具有 optional chaining运算符(我见过它也称为安全导航运算符),这将允许您的示例编写为:

var a = b?.c?.d;

来自 MDN docs :

The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

关于javascript - 安全地访问 Javascript 嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18178406/

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