在 Node.js 中,如果您以“?? null”结束一系列选项,您将以该值或 null 结束,这是否正确? (即避免未定义)

问题描述 投票:0回答:1

假设你有一个非常大的json -> 对象,比如

const cc = stuff.galaxies[13].stars[2099].planets["Jingo"].cities

我混合了两个数组并命名为 json。

当然,一路上可能会缺少一些东西。

我倾向于这样做:

const cc = stuff.galaxies?[13]?.stars?[2099]?.planets?["Jingo"]?.cities ?? null

这似乎确实有效,它会导致 cc 成为(在本例中)“城市”数组,或者为 null。 (没有“未定义”。)

或者另一个例子可能是

const j = stuff.galaxies?[13]?.stars?[2099]?.planets?["Jingo"] ?? null

这是正确的吗? TY。除非您真的是一位专注于 Node 的专家,否则很难了解 Node 中可选选项的所有细节。

node.js optional-chaining
1个回答
0
投票

是的,您使用可选链接 (

?.
) 和无效合并 (
??
) 是正确的!

可选链接允许您安全地访问深度嵌套的属性,而不会在链的任何部分是

undefined
null
时遇到错误。如果缺少任何部分,则返回
undefined
,然后空合并运算符确保如果结果为
undefined
,则
cc
(
or j
) 将设置为
null

所以在你的例子中:

const cc = stuff.galaxies?.[13]?.stars?.[2099]?.planets?.["Jingo"]?.cities ?? null;
const j = stuff.galaxies?.[13]?.stars?.[2099]?.planets?.["Jingo"] ?? null;

两者都会按您的预期工作。如果沿途缺少任何属性,则

cc
j
将为
null
,避免任何
undefined
值。这使得您的代码在使用深层嵌套结构时更加安全和清晰!

© www.soinside.com 2019 - 2024. All rights reserved.