Javascript MyApphow如何检查;MyApp.User.current.language的类型“;
可能重复:Javascript MyApphow如何检查;MyApp.User.current.language的类型“;,javascript,Javascript,可能重复: 这感觉不对。这个if语句可以用更好的方式编写吗?一个简单的方法是: try { console.log(MyApp.User.current.language); } catch(e) {} 或者,如果MyApp.User.current存在,但MyApp.User.current.language不存在,则您不希望输出“未定义”,则可以使用以下方法: try { if (typeof MyApp.User.current.language != 'undefin
这感觉不对。这个if语句可以用更好的方式编写吗?一个简单的方法是:
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
捕获当MyApp
或MyApp.user
或MyApp.user.current
未定义时的情况,因此您不必单独测试它们。您可以执行重构并将该条件放入函数中:
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;
}
那Siag是从哪里来的?谢谢richard。固定的。这是一个c&p错误。
var lang;
if(lang = getCurrentLang()) {
console.log(lang);
}
function getCurrentLang() {
return MyApp && MyApp.User && MyApp.User.current && MyApp.User.current.language;
}