检查嵌套属性是否存在的正确方法是什么?
if (openResult.notification) {
if (openResult.notification.payload) {
if (openResult.notification.payload.additionalData) {
if (openResult.notification.payload.additionalData.sensorOpenWarning) {
// now do sth with openResult.notification.payload.additionalData
}
}
}
}
答案 0 :(得分:0)
使用try catch
var obj;
try{
console.log(obj.one.two.three.four)
}catch(e){
console.log("obj is undefined")
}
答案 1 :(得分:0)
您可以使用此缩写形式:
const prop2 = ((obj || {}).prop1 || {}).prop2;
应用于您的代码将是:
const sensorOpenWarning = ((openResult || {}).notification || {}).payload || {}).additionalData || {}).sensorOpenWarning;