我想检查复杂对象链中是否缺少任何对象。
我想出了以下解决方案,是否有更好的方法可以实现相同目的?
var lg = console.log;
var t = { a:{a1: 33, a12:{ aa1d: 444, cc:3 } }, b:00};
var isDefined = function(topObj, propertyPath) {
if (typeof topObj !== 'object') {
throw new Error('First argument must be of type \'object\'!');
}
if (typeof propertyPath === 'string') {
throw new Error('Second argument must be of type \'string\'!');
}
var props = propertyPath.split('.');
for(var i=0; i< props.length; i++) {
var prp = props[i];
lg('checking property: ' + prp);
if (typeof topObj[prp] === 'undefined') {
lg(prp + ' undefined!');
return false;
} else {
topObj = topObj[prp];
}
}
return true;
}
isDefined(t, 'a.a12.cc');
最佳答案
您的概念还可以,但是必须更改代码。当属性具有null
值时,它不能具有任何属性。尝试访问null
上的属性会导致错误。要解决此问题,请使用:
for (var i=0; i<props.length; i++) {
var prp = props[i],
val = topObj[prp];
lg('checking property: ' + prp);
if (typeof val === 'undefined') {
lg(prp + ' undefined!');
return false;
} else if (val === null) {
return i === props.length-1; // True if last, false otherwise
} else {
topObj = val;
}
}