복잡한 개체 체인에 개체가 누락되었는지 확인하고 싶습니다. 다음과 같은 해결책을 찾았습니다. 더 좋은 방법은 있습니까?오브젝트 체인에서 'undefined'를 확인하는 방법은 무엇입니까?
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');
가능한 중첩 된 개체 키의 존재에 대한 자바 스크립트 테스트 (http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key) –
@Felix 질문 중복이 아닙니다. 복제물은 프로토 타입 체인의 상속 속성을 고려하지 않습니다. –
@RobW : 요청하지 않았으며 변경하기 쉽습니다. 전반적인 접근 방식은 변하지 않습니다. –