简体   繁体   English

在JavaScript / TypeScript中将项目添加到数组的末尾

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

I have this do while loop 我有这个做while循环

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. 即使在while循环的其他迭代中,也总是从0开始。

What else do i need to add to the .push method 我还需要添加什么到.push方法中

使用concat而不是push

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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