MyApphow检查“typeof MyApp.User.current.language”

时间:2011-10-12 15:28:37

标签: javascript

  

可能重复:
  javascript test for existence of nested object key

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语句可以用更好的方式写出来吗?

2 个答案:

答案 0 :(得分: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 :(得分: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;
}