【问题标题】:use Optional Chaining to check for null or undefined [duplicate]使用可选链接检查 null 或 undefined [重复]
【发布时间】:2022-12-14 22:37:35
【问题描述】:

我正在使用这段代码

data?.response[0]?.Transaction[0]?.UID;

这里 Transaction 密钥不可用,我正在获取

ERROR TypeError: Cannot read properties of undefined (reading '0')

我试图使用 Optional Chaining 检查 null 或 undefined,而不是使用 if 检查它。

【问题讨论】:

  • 您能否提供您正在使用的对象的示例蓝图?

标签: javascript typescript


【解决方案1】:

Optional chaining 也适用于数组索引:

data?.response?.[0]?.Transaction?.[0]?.UID

例如:

const obj = {
  arr: [1]
};

console.log('exists:', obj?.arr?.[0]);
console.log('does not exist:', obj?.another_arr?.[0]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 2011-09-19
    • 1970-01-01
    • 2019-08-02
    相关资源
    最近更新 更多