如何防止TypeError空白未定义?

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

Int

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

// 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

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

是否有更清洁/更快/更聪明的方式来做到这一点?

ether1984 回答:如何防止TypeError空白未定义?

使用

try{
if(response.data.variable_to_check!==undefined){
console.log("undefined");
}
}
catch(err){console.log(err.message)}
本文链接:https://www.f2er.com/2955266.html

大家都在问