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

Error when trying to check typeof undefined json object

本文关键字:类型 出错 对象 json 检查 未定义      更新时间:2023-09-26

当我试图检查[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];
    }

错误:未捕获类型错误:无法读取未定义的属性"register_mobile"

您需要像一样检查每个属性

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];
}