速记 javascript 对象嵌套属性访问,没有"Cannot read property 'xxx' of undefined"错误



我一直在寻找一种访问嵌套级别对象属性而不会出现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);

相关内容

最新更新