我一直在寻找一种访问嵌套级别对象属性而不会出现Cannot read property 'xxx' of undefined
错误的方法。
我还想轻松地默认可能不存在的值。
我遇到这种情况的唯一方法是:
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);