【问题标题】:How do I prevent TypeError blank is undefined? [duplicate]如何防止 TypeError 空白未定义? [复制]
【发布时间】:2020-04-01 13:45:09
【问题描述】:

当目标位于对象深处时,是否有更简单的方法来检查 JavaScript 中是否定义了变量? 例如。

// Lets assume this: 
response = {
   status: "simple-message"
}

// running this:
if (response.data.variable_to_check !== undefined) console.log('undefined');
// will result in this:
> TypeError: response.data is undefined

在 PHP 中我可以运行等效的检查:

if (!($response->data->variable_to_check ?? false)) die("Handled Undefined Error");
// will result in this:
> Handled Undefined Error

我知道我可以通过检查从根开始的每个项目来手动迭代以查看它是否已定义,但这似乎很乏味。并将所有内容包装在 try/catch 中。

是否有更清洁/更快/更智能的方法来做到这一点?

【问题讨论】:

标签: javascript error-handling undefined typeerror


【解决方案1】:

使用

try{
if(response.data.variable_to_check!==undefined){
console.log("undefined");
}
}
catch(err){console.log(err.message)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    相关资源
    最近更新 更多