【问题标题】:Shorthand javascript object nested property access without "Cannot read property 'xxx' of undefined" error [duplicate]没有“无法读取未定义的属性'xxx'”错误的速记javascript对象嵌套属性访问[重复]
【发布时间】:2021-08-02 05:06:39
【问题描述】:

我一直在寻找一种方法来访问嵌套级别对象属性而不会收到Cannot read property 'xxx' of undefined 错误。

我还想轻松地默认可能不存在的值。

【问题讨论】:

    标签: javascript object shorthand


    【解决方案1】:

    我遇到类似情况的唯一方法是:

    var someObject = {};
    var myVar = someObject?.that?.might?.or?.mightnot?.have?.this?.property ?? 'default';
    
    if (someObject?.that?.might?.or?.mightnot?.have?.this?.property === 'some-check') {
        // this throws no error
    }
    
    console.log(myVar);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 2023-03-20
      • 2018-02-04
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      相关资源
      最近更新 更多