如果您以“?? null”结束一系列选项,您会以该值还是以 null 结束(即避免未定义)?

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

假设你有一个非常大的物体,例如:

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

我混合了数组和对象。

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

我倾向于这样做:

const cc = stuff.galaxies?[13]?.stars?[2099]?
               .planets?["Jingo"]?.cities ?? null
if (cc === null) {
    // something was missing in the json at one of
    // galaxies, the 13th index of galaxies,
    // stars, the 2099th index of stars,
    // planets dictionary, or the "Jingo" item of planets,
    // or the cities entry (whether that is an array or object)
}

这似乎确实有效,它会导致

cc
成为城市数组,或
null
(没有
undefined
)。

或者另一个例子可能是

const j = stuff.galaxies?[13]?.stars?[2099]?.planets?["Jingo"] ?? null
if (cc === null) {
    // something was missing in the json at one of
    // galaxies, the 13th index of galaxies,
    // stars, the 2099th index of stars,
    // or planets dictionary, or the "Jingo" item of planets
}

这是正确的吗?

javascript node.js
1个回答
1
投票

这是可选链的正确格式:

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

空合并运算符 (

??
) 确保如果左侧计算结果为
null
undefined
,则返回右侧(在您的情况下为
null
)。

注意:仅null

undefined
,而不是
0
false
或其他非真实值。这与 OR 运算符 (
||
) 不同,OR 运算符由 
any 非真值满足 (null
, 
undefined
, 
0
, 
false
, ...)

回复:您示例中的

?? null

。通过可选链接,如果链的某些部分失败,您将收到 
undefined
。如果您添加空合并是为了“捕获”失败的链,则没有必要(除非您特别希望结果为 
null
)。

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