与hasOwnProperty混淆

我编写了下面的代码,以及更多,以快速构建3屏幕Web应用程序的原型。 不打算用它来生产。 该项目即将完成,但有一个问题困扰着我。 我收到错误 – Cannot read property 'first_name' of undefined ,即使先检查对象是否将属性报告为未定义。 实现代码不是一个如何处理这些事情的例子,但为什么它不起作用? 为了防止上下文的困难,我甚至克隆了数组 – 可能是不必要的。 是什么导致未定义的错误?

  $.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 += '
' + '
SEAT ' + seats[i].seat + '
' + '
' + seats[i].hasOwnProperty('passenger') ? seats[i].passenger.first_name + ' ' + seats[i].passenger.last_name : '' + '
' + '
 ' + seats[i].hasOwnProperty('passenger') ? 'Reserved' : 'Available' + '
' + '
'; } } } $('div.right-top-controls').after(template); } }, error: function() { alert('error!'); } });

请指教。

谢谢。

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);