2011-10-12 31 views
1

可能重複:
javascript test for existence of nested object keyMyApphow檢查 「的typeof MyApp.User.current.language」

if (typeof MyApp != 'undefined' && 
    typeof MyApp.User != 'undefined' && 
    typeof MyApp.User.current != 'undefined' && 
    typeof MyApp.User.current.language != 'undefined') { 

    console.log(MyApp.User.current.language); 
} 

這種感覺是錯誤的。這個if語句可以用更好的方式寫出來嗎?

+1

那個'Siag'從哪裏來的? –

+0

謝謝理查德。固定。是一個C&P錯誤。 – Simon

回答

1

一個簡單的方法是這樣的:

try { 
    console.log(MyApp.User.current.language); 
} catch(e) {} 

,或者如果你不想「不確定」是輸出,如果MyApp.User.current存在,但MyApp.User.current.language沒有,那麼你可以使用這個:

try { 
    if (typeof MyApp.User.current.language != 'undefined') { 
     console.log(MyApp.User.current.language); 
    } 
} catch(e) {} 

try/catch捕獲MyAppMyApp.userMyApp.User.current未定義的情況,因此您不必單獨測試它們。

1

你可以執行decompose conditional重構,並將該條件的函數:

if (currentLanguageIsDefined()) { 
    console.log(MyApp.User.current.language); 
} 

function currentLanguageIsDefined() { 
    return typeof MyApp != 'undefined' && 
      typeof MyApp.User != 'undefined' && 
      typeof MyApp.User.current != 'undefined' && 
      typeof MyApp.User.current.language != 'undefined'; 
} 

...或者你可以採取的操作&&評估返回的最後一個值的事實優勢:

var lang; 
if(lang = getCurrentLang()) { 
    console.log(lang); 
} 

function getCurrentLang() { 
    return MyApp && MyApp.User && MyApp.User.current && MyApp.User.current.language; 
}