JS:防止访问未定义对象的属性时出错

JS: Prevent Error if Accessing Attributes of Undefined Object

本文关键字:属性 出错 对象 未定义 访问 JS      更新时间:2023-09-26

我的目标:测试对象的属性是否为/返回true。但是,在某些情况下,对象是未定义的。


这没问题。脚本继续正常运行。

if(somethingUndefined){ }


但是,如果我试图访问未定义对象的属性,这将生成一个错误并停止脚本。

if(somethingUndefined.anAttribute){ }


现在,这就是我用来解决问题的方法:

if(somethingUndefined && somethingUndefined.anAttribute){ }


还有别的办法吗?如果程序试图访问未定义对象的属性,全局设置可能会返回false?

如果您有许多类似if(somethingUndefined && somethingUndefined.anAttribute){ }的If语句,那么当它未定义时,您可以为它分配一个空对象。

var somethingUndefined = somethingUndefined || {};
if (somethingUndefined.anAttribute) {
}

您可以利用JavaScript在if条件内分配变量的能力,并在通过第一个嵌套对象后遵循此模式进行更快的检查。

JsPerf

var x; 
if(
   (x = somethingUndefined) && // somethingUndefined exists?
   (x = x.anAttribute) && // x and anAttribute exists?
   (x = x.subAttrubute) // x and subAttrubute exists?
){
}

与传统

if(
    somethingUndefined && // somethingUndefined exists?
    somethingUndefined.anAttribute && // somethingUndefined and anAttribute exists?
    somethingUndefined.anAttribute.subAttribute // somethingUndefined and anAttribute and subAttribute exists?
){
}

问题中的处理方式通常是用javascript进行的。如果你发现自己经常使用这个,你可以把它抽象成一个函数,让自己的东西更干净一点,比如:

if (attrDefined(obj, 'property')) {
  console.log('it is defined, whoo!');
}
function attrDefined(o, p){ return !!(o && o[p]) }