简体   繁体   中英

Adding items to the end of an array in JavaScript/TypeScript

I have this do while loop

trucks = [];
fetchdata(){
    this.trucks = [];

    do {

     this._reportService.getReports({
        ..//pagination stuff here
        })
        .subscribe(res=> {
          this.trucks.push(res.rawdatatrucks);
        })
    } while(i<this.totalRecords);
    console.log(this.trucks)

}

THe above works but data is pushed in this form

0:[
    0:[ ...truck data stuff ],
    1:[ ...truck data stuff ],
    2:[ ...truck data stuff ],
    3:[ ...truck data stuff ],
 ],
 1:[
    0:[ ...truck data stuff ],
    1:[ ...truck data stuff ],
    2:[ ...truck data stuff ],
    3:[ ...truck data stuff ],
 ],

What i was looking forward to get is to append the data at the end of the array such that i would get

console.log(this.trucks)

     0:[ ...truck data stuff ],
    1:[ ...truck data stuff ],
    2:[ ...truck data stuff ],
    3:[ ...truck data stuff ],
    4:[ ...truck data stuff ],
    5:[ ...truck data stuff ],
    6:[ ...truck data stuff ],
    .......

A response from the server that is

console.log(res.rawdatatrucks);

always starts at 0 even in the other iterations of the while loop.

What else do i need to add to the .push method

使用concat而不是push

this.trucks = this.trucks.concat(res.rawdatatrucks);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM