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

时间:2017-10-05 01:45:15

标签: javascript typescript

我有这个做while 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)

}

以上情况有效,但数据以此形式推送

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 ],
 ],

我期待得到的是将数据追加到数组末尾以便我得到

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 ],
    .......

服务器的响应

console.log(res.rawdatatrucks);
即使在while循环的其他迭代中,

始终从0开始。

我需要在.push方法中添加什么

1 个答案:

答案 0 :(得分:2)

使用concat代替push

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