首页 > 解决方案 > 速记 javascript 对象嵌套属性访问,没有“无法读取未定义的属性 'xxx'”错误

问题描述

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

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

标签: javascriptobjectshorthand

解决方案


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

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);


推荐阅读