2017-05-04 77 views
1

我想從API中循環對象結果,並將其推入數組中。如何將數據推送到數組,當循環對象

historys: any = []; 

Loop。

Object.keys(response['orderdetail']).forEach(function(index, key) { 
    console.log(key, response['orderdetail'][index]) 
    this.historys.push(response['orderdetail'][index]); 
}); 

樣子this.historyshistorys: any = [];, 如何做到這一點。

+0

'this'在'this.historys.push'中指的是什麼?你在哪裏定義'historys'? – Satpal

+0

其實第一個參數forEach回調不是索引而是第二個索引 – binariedMe

回答

2

此問題在foreach函數中,您已經丟失了this上下文並且它已更改。您可以將上下文作爲參數傳遞給foreach。

Object.keys(response['orderdetail']).forEach(function(index, key) { 
    console.log(key, response['orderdetail'][index]) 
    this.historys.push(response['orderdetail'][index]); 
}, this); 
// ^^^^ this will keep the this context 
+0

哇,謝謝。 – ThunderBirdsX3

相關問題