【发布时间】: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 中。
是否有更清洁/更快/更智能的方法来做到这一点?
【问题讨论】:
-
github.com/tc39/proposal-optional-chaining 使用 babel 发出较旧的 javascript 等效项。
-
@ASDFGerte,这就是我想要的,是的。很高兴看到它快到了。而“嵌套对象”正是我所寻找的。当时想不出这句话。
标签: javascript error-handling undefined typeerror