2017-04-13 57 views
0

我覺得我這樣做,因此我需要檢查的是,前述變量不是undefined檢查下一個鏈中前:Javascript - 如何檢查父對象是否未定義?

if(this.props.someVar && this.props.someVar.data) { 
    // do something with this.props.someVar.data ... 
} 

這將是理想的只是這樣做:

if(this.props.someVar.data) { 
    // This throws an error because I haven't checked if `this.props.someVar` exists beforehand. 
} 

有沒有更容易/更短的方式來這麼做,最好使用純Javascript?

+1

檢查'someVar'是否使用'!= undefined'語句未定義。 – Oen44

+0

我知道,不是「純粹的」JS,但是使用[immutableJS](https://facebook.github.io/immutable-js/docs/#/)具有諸如[getIn](https ://facebook.github.io/immutable-js/docs/#/Collection/getIn) – thedude

+0

嘗試使用'!!'與父母然後測試孩子 –

回答

-1

我討厭這個。最簡單的方法是使用這樣的try catch

try { 
    // do something with this.props.someVar.data 
} catch (e) { 
    if (e instanceof TypeError) { 
     // TypeError happens when an object in the chain is undefined 
    } 
} 
+0

爲什麼downvote? – Mtihc

+1

這既不短也不易理解 –