JS:防止访问未定义对象的属性时出错
JS: Prevent Error if Accessing Attributes of Undefined Object
我的目标:测试对象的属性是否为/返回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]) }
相关文章:
- AngularJS指令出错-无法读取属性'编译'的未定义
- 解析 /page.xhtml 时出错:跟踪错误[行: 42] 与元素类型“id”关联的属性“{1}”应使用左引号
- 为JavaScript类属性赋值时出错
- 访问console.log中的数据属性时出错
- 在Spring.message属性中添加新行时出错
- Javascript:“;无法读取属性'addEventListener'“为空”;尝试删除子项时出错
- '无法设置未定义'的属性;应用绑定时出错
- 使用Internet Explorer进行react redux trySubscribe时出错(无法获取未定义的属性“
- 在 Javascript 中使用警报时出错(对象的属性“alert”不是函数)
- css 可见性属性和 javascript setTimeout 方法出错
- 加载图表时出错 未捕获的类型错误:无法读取未定义的属性“到小写”
- 在网格视图中获取属性“行”时出错
- Metro Javascript.对项目进行分组时出错.ui.js firstItemIndexHint 属性
- 解析属性名称时出错
- Ember Data 1.0 加载路由时出错:类型错误:无法设置未定义的属性“类型键”
- 将 req.body 属性复制到猫鼬模型中时出错
- 尝试在火狐扩展中获取标题属性时出错
- JS:防止访问未定义对象的属性时出错
- 避免'无法读取未定义'的属性;映射数据时出错
- TYPO3 Neos:Apply content属性在JavaScript中运行时出错