对象长度始终为0

时间:2017-02-04 10:13:27

标签: javascript ionic-framework

当我console.log( accomdationSearchResultsData.length );时,我总是在控制台中获得0的长度,但实际上有2个对象

对象

enter image description here

示例代码

accommodationById() {
    var accomdationSearchResultsData = [];
    var hotelSearchCount = 0;

    this.api.accommodationById( this.accomodationId ).subscribe( accomdationResponse => {
        var accomdation_id, accomdation_type, accomdation_hotel, accomdation_id, accomdation_rate, accomdation_hotel_id, accomdation_hotel_name, accomdation_hotel_city, accomdation_hotel_street, accomdation_hotel_state, accomdation_hotel_checkin_time, accomdation_hotel_checkout_time;

        var accomdation_id = accomdationResponse.id;
        var accomdation_type = accomdationResponse.name;
        this.accomodationType = accomdation_type;

        for (var i = 0; i < accomdationResponse.Rooms.length; i++){
          accomdation_hotel = accomdationResponse.Rooms[i].hotel;
          accomdation_rate = accomdationResponse.Rooms[i].rate;

          this.api.getHotelByAPI( accomdation_hotel ).subscribe( hotelResponse => {

            accomdation_hotel_id = hotelResponse.id;
            accomdation_hotel_name = hotelResponse.name;
            accomdation_hotel_city = hotelResponse.city;

            accomdationSearchResultsData.push({
              accomdation_id: accomdation_id,
              accomdation_type: accomdation_type,
              accomdation_hotel: accomdation_hotel,
              accomdation_rate: accomdation_rate,
              accomdation_hotel_id: accomdation_hotel_id,
              accomdation_hotel_name: accomdation_hotel_name,
            });
          });
        }

        this.accomodationResults = accomdationSearchResultsData;
        console.log( accomdationSearchResultsData.length );
    });
}

1 个答案:

答案 0 :(得分:-2)

试试这个

setTimeout(function () {
        console.log(accomdationSearchResultsData.length);
    }, 2000);

我认为您只需在流程完成之前记录它。