2012-07-27 3 views
3

복잡한 개체 체인에 개체가 누락되었는지 확인하고 싶습니다. 다음과 같은 해결책을 찾았습니다. 더 좋은 방법은 있습니까?오브젝트 체인에서 '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'); 
+1

가능한 중첩 된 개체 키의 존재에 대한 자바 스크립트 테스트 (http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key) –

+0

@Felix 질문 중복이 아닙니다. 복제물은 프로토 타입 체인의 상속 속성을 고려하지 않습니다. –

+0

@RobW : 요청하지 않았으며 변경하기 쉽습니다. 전반적인 접근 방식은 변하지 않습니다. –

답변

3

개념은 정상이지만 코드를 변경해야합니다. 속성에 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; 
    } 
} 
+0

위대한 catch, thanks – krul

+1

@krul 다른 캐치 :'var lg = console.log; '를 사용하지 마십시오. 이것은 Chrome에서 중단됩니다. 대신에'console.log.bind (console);'을 사용하면'console.log'의 컨텍스트를 보존 할 수 있습니다. –

+0

롭 승, 고마워, 나는 그것을 알고 있지만 어쨌든, 관심을 지불하지 않았다. – krul

7

당신은 다음과 같이 더 간단하게 함수를 정의 할 수 있습니다 :

var isDefined = function(value, path) { 
    path.split('.').forEach(function(key) { value = value && value[key]; }); 
    return (typeof value != 'undefined' && value !== null); 
}; 

예를 들어 작업 jsfiddle에.

관련 문제