2017-02-07 25 views
3
const items = []; 
Meteor.http.call("GET", url,function(error,result){ 
    $.each(JSON.parse(result.content), function(key, value){ 
    items.push(value) 
    }); 
}); 

下面的代碼返回長度爲0的非空數組項目。 如何迭代數組或通過鍵提取所有值到數組?
enter image description here流星中長度= 0的非空陣列

+0

它在哪裏長度爲0返回數組?你在哪裏記錄'物品'得到長度爲0? –

+0

console.log(items.length)= 0 +在屏幕上你可以看到「Array [0]」 –

+0

你在哪裏登錄它?如果您將它記錄在Metor回調函數之外,您可能會看到,因爲異步函數尚未完成。 –

回答

4

Meteor.http.call是一個帶回調的異步函數。一個快速的方法我能想到做你想要的是以下幾點:

const items = []; 
Meteor.http.call("GET", url,function(error,result){ 
    $.each(JSON.parse(result.content), function(key, value){ 
    items.push(value) 
    }); 
    handleItems(items); 
}); 

function handleItems(items) { 
    console.log(items.length) // 1 
    // Do what you want with the items array here. 
} 
+0

是的,當在回調中執行的代碼一切正常時。我可以如何使用原始長度的外部回調數組? –

+0

最簡單的,你不能。您需要處理回調中的事情,因爲代碼是異步的。也許如果你告訴我更多關於你想要達到什麼的背景,我可以提出其他建議嗎? –

+0

我想從api(json數據)獲取數據並將其發送到bar函數(plot)from react-chartjs –