2016-06-06 2 views
-1

3 개의 화면 웹 애플리케이션을위한 프로토 타입을 신속하게 구축하기 위해 아래 코드와 몇 가지를 썼습니다. 프로덕션을 위해 사용할 계획이 아닙니다. 프로젝트는 거의 끝났지 만, 당혹 스럽다는 한 가지 문제가 있습니다. 객체가 정의되지 않은 것으로보고 된 속성을 가지고 있는지 여부를 먼저 확인하더라도 오류가 발생합니다 (Cannot read property 'first_name' of undefined). 코드를 이해하는 것은 그러한 것들이 어떻게 처리되어야하는지에 대한 예가 아니라 왜 작동하지 않는가? 컨텍스트 어커런스를 방지하기 위해 배열을 복제하기도합니다. 아마도 불필요한 것일 것입니다. 정의되지 않은 오류의 원인은 무엇입니까?hasOwnProperty와의 혼동

$.ajax({ 
     url: '/api/v1/departures/' + routeID + '/', 
     method: 'GET', 
     headers: { 
      'Authorization': 'Token '+ owner_token] 
     }, 
     contentType:'application/json', 
     success: function(departures) { 
      console.log('departures: ' + JSON.stringify(departures)); 
      if (departures && (0 < departures.length)) { 
       var template = ''; 
       for (var j = 0; j < departures.length; j++) { 
        if (departures[j].route == routeID) { 
         var seats = (departures[j].seats).slice(0); 
         for (var i = 0; i < seats.length; i++) { 
          template += '<div class="right-seat" data-id="' + seats[i].seat + '">' + 
           '<div class="right-seat-place">SEAT ' + seats[i].seat + '</div>' + 
           '<div class="right-seat-name">' + 
           seats[i].hasOwnProperty('passenger') ? seats[i].passenger.first_name + ' ' + seats[i].passenger.last_name : '' + 
           '</div>' + 
           '<div class="right-seat-reserved"><i class="glyphicon glyphicon-check"></i>&nbsp;' + 
           seats[i].hasOwnProperty('passenger') ? 'Reserved' : 'Available' + 
           '</div>' + 
           '</div>'; 
         } 
        } 
       } 
       $('div.right-top-controls').after(template); 
      } 
     }, 
     error: function() { 
      alert('error!'); 
     } 
    }); 

알려 주시기 바랍니다.

감사합니다.

+2

승객에게는 first_name 속성이 없을 수 있습니다. 이것에 대한 검사는 없습니다. –

+0

사실이지만 내 질문이나 오류와 무슨 상관이 있습니까? –

+0

기본적으로 귀하의 검색자가 여객이라는 속성을 가지고 있지만 좌석 = {passenger : undefined}와 같이 정의되지 않았습니다. seat.hasOwnProperty ('passenger') – juvian

답변

2

hasOwnProperty은 개체에 해당 이름의 속성이 있는지 확인합니다. 그 가치가 무엇인지는 확인하지 않습니다. 그 값은 undefined 일 수 있습니다.

// Doesn't have the property and accessing it returns undefined 
 
var A = {}; 
 
console.log(A.hasOwnProperty('prop')); 
 
console.log(A.prop); 
 

 

 
// Has the property and the value is not undefined 
 
var B = { 
 
    prop: 1 
 
}; 
 
console.log(B.hasOwnProperty('prop')); 
 
console.log(B.prop); 
 

 
// Has the property AND it's value is undefined 
 
var C = { 
 
    prop: undefined 
 
}; 
 
console.log(C.hasOwnProperty('prop')); 
 
console.log(C.prop);

seats[i]이 아주 잘 passenger 속성을 가질 수 있다는 것을 의미하지만, 값이 여전히 undefined이 될 수는 있습니다. 당신은 본질적으로 ternary operation during string concatenation.를 사용하는 문제도있다

, +는 평가 조건 전에 발생하는 연결 결과 ?:보다 더 높은 우선 순위를 가지고 있습니다. 이 문제를 해결하려면 괄호 안에 삼항 문자를 넣으십시오.

template += '<div class="right-seat" data-id="' + seats[i].seat + '">' + 
       '<div class="right-seat-place">SEAT ' + seats[i].seat + '</div>' + 
       '<div class="right-seat-name">' + 
       (seats[i].hasOwnProperty('passenger') ? seats[i].passenger.first_name + ' ' + seats[i].passenger.last_name : '') + 
       '</div>' + 
       '<div class="right-seat-reserved"><i class="glyphicon glyphicon-check"></i>&nbsp;' + 
       (seats[i].hasOwnProperty('passenger') ? 'Reserved' : 'Available') + 
       '</div>' + 
      '</div>'; 
+0

이 올바른지 확인해야합니다. 덕분에 마이크 C – JordanHendrix

+0

이 적합합니다. 내 상황에서는 불행히도 그렇지 않습니다. –

+0

@MosheShmukler 아마도'console.log (seats [i] .passenger)'를 시도해보아야 할 것입니다. 왜냐하면 그 값을 'undefined'로 설정하면 그 에러를 얻을 수있는 유일한 방법이기 때문입니다. 그리고 hasOwnProperty 검사를 통과시키는 유일한 방법은 객체가 그 이름으로 속성을 가지고 있지만 값이 'undefined'인 경우입니다. –