2016-09-27 2 views
-6

없이 속성을 확인하는 방법이 var o = $scope['reservation']['bookings'][bookingKey]['meals']내가</p> <pre><code>if (o.hasOwnProperty('checkedProperty') { // code } </code></pre> <p>을 수행 할 때 hasOwnProperty

같은 개체가 나는 오류 Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined 있습니다.

if (o['checkedProperty']) { 

    // code to do if my object 'o' has 'checkedProperty' 

} 

하지만 오류가 있습니다 :

내가 너무 노력 Uncaught TypeError: Cannot read property '26' of undefined을.

이 속성을 확인하려면 어떻게해야합니까?

+1

'O' 인'객체 인 경우 –

+0

체크 undefined''첫째, 다음 진행 undefined' :

확인 o 경우 실제로 개체입니다. – vlaz

+0

열심히하고 싶지 않다면'try/catch'. – yoavmatchulsky

답변

1

처음에 개체가 없을 때 개체에 속성이 있는지 확인할 수 없습니다.

if (typeof o !== "undefined" && o.hasOwnProperty('checkedProperty')) { 
+0

'o'가'null' 인 경우에도 실패합니다. 일반적인 해결책 :'if (o! = null && o.hasOwnProperty ('checkedProperty')) {'이것은'o'가 선언되었다고 가정합니다. 그렇지 않으면 : if (typeof o! == 'undefined'&& o! == null && o.hasOwnProperty ('checkedProperty')) {' –

관련 문제