检查是否定义了像obj.prop.otherprop.another这样的对象属性的推荐方法是什么?
if(obj && obj.prop && obj.prop.otherprop && obj.prop.otherprop.another)
Run Code Online (Sandbox Code Playgroud)
这很好用,但足够难看.
最有效的方法是在 try{} catch(exception){} 块中检查 obj.prop.otherprop.another 。如果剩下的都存在的话,这将是最快的;否则异常将被处理。
var a = null;
try {
a = obj.prop.otherprop.another;
} catch(e) {
obj = obj || {};
obj.prop = obj.prop || {};
obj.prop.otherprop = obj.prop.otherprop || {};
obj.prop.otherprop.another = {};
a = obj.prop.otherprop.another ;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
177 次 |
| 最近记录: |