尝试检查未定义的json对象的类型时出错

时间:2013-08-15 12:57:33

标签: javascript jquery

当我试图检查[action]是否已定义时,我不断收到javascript错误。

    if((typeof array_from_php.api_description[mobile_type][action]) != 'undefined') {
        console.log('defined');
        api = array_from_php.api_description[mobile_type][action];
    } else {
        console.log('undefined');
        mobile_type = 0;
        api = array_from_php.api_description[mobile_type][action];
    }

错误: 未捕获的TypeError:无法读取未定义的属性'register_mobile'

1 个答案:

答案 0 :(得分:1)

你需要检查每个属性,如

if(array_from_php && array_from_php.api_description && array_from_php.api_description[mobile_type] && (typeof array_from_php.api_description[mobile_type][action]) != 'undefined') {
    console.log('defined');
    api = array_from_php.api_description[mobile_type][action];
} else {
    console.log('undefined');
    mobile_type = 0;
    api = array_from_php.api_description[mobile_type][action];
}