Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS:在访问未定义对象的属性时防止出错_Javascript - Fatal编程技术网

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

Javascript JS:在访问未定义对象的属性时防止出错,javascript,Javascript,我的目标:测试对象的属性是否为/返回true。但是,在某些情况下,对象是未定义的 var somethingUndefined = somethingUndefined || {}; if (somethingUndefined.anAttribute) { } 这没问题。脚本将正常继续 if(somethingUndefined){} 但是,如果尝试访问未定义对象的属性,则会生成错误并停止脚本 if(somethingUndefined.anaAttribute){} 现在,这就是

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

var somethingUndefined = somethingUndefined || {};

if (somethingUndefined.anAttribute) {

}

这没问题。脚本将正常继续

if(somethingUndefined){}


但是,如果尝试访问未定义对象的属性,则会生成错误并停止脚本

if(somethingUndefined.anaAttribute){}


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

if(somethingUndefined&&somethingUndefined.anaAttribute){}



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

如果有许多if语句,如
if(somethingUndefined&&somethingUndefined.anaAttribute){}
,则可以在未定义时为其分配空对象

var somethingUndefined = somethingUndefined || {};

if (somethingUndefined.anAttribute) {

}

您在问题中使用的方式通常与javascript中使用的方式相同。如果您发现自己经常使用它,您可以将其抽象为一个函数,让事情变得更干净,例如:

if (attrDefined(obj, 'property')) {
  console.log('it is defined, whoo!');
}

function attrDefined(o, p){ return !!(o && o[p]) }

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

与传统

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

}

somethingUndefined&&somethingUndefined.anAttribute
是一种标准做法,如果我们能够检查嵌套属性而不会出现致命错误,我会非常高兴。使用wpapiatm和我的代码到处都是这样的<代码>如果(this.post.featured\u image&&this.post.featured\u image.media\u details&&this.post.featured\u image.media\u details.size&&this.post.featured\u image.media\u details.size&&this.post.featured\u image.media\u details.size)