为什么arr数据只在json函数中可用?第一个console.log返回数据,第二个是空数组?我是否需要结束第一次调用或以某种方式复制到动态数组?
var inputURL;
var start = "2016-09-01";
var end = "2016-09-06";
var arr = [];
var stock = ["AZN.L", "GOOGL", "AAPL"];
var arrayLength = stock.length;
for (var i = 0; i < arrayLength; i++) {
itern(stock[i]);
};
function itern (stock) {
inputURL = "http://query.yahooapis.com/v1/public/yql" +
"?q=select%20*%20from%20yahoo.finance.historicaldata%20" +
"where%20symbol%20%3D%20%22"
+ stock + "%22%20and%20startDate%20%3D%20%22"
+ start + "%22%20and%20endDate%20%3D%20%22"
+ end + "%22&format=json&env=store%3A%2F%2F"
+ "datatables.org%2Falltableswithkeys";
// Get the data
d3.json(inputURL, function (error, data) {
data.query.results.quote.forEach(function (d) {
d.date = parseDate(d.Date);
// console.log(d.date);
d.high = +d.High;
d.low = +d.Low;
arr.push({
company: stock,
date: d.date,
high: d.high,
low: d.low,
sortable: true,
resizeable: true
});
});
console.log(arr); //returns arr with data
});
console.log(arr); // returns arr[]
};
答案 0 :(得分:0)
d3.json是一个异步函数,因此只有在执行回调后才会填充arr
。您可以在回调中填充arr
之后调用函数,如下所示:
var dataAvailable = function() {
console.log(arr);
};
d3.json(inputURL, function (error, data) {
data.query.results.quote.forEach(function (d) {
d.date = parseDate(d.Date);
// console.log(d.date);
d.high = +d.High;
d.low = +d.Low;
arr.push({
company: stock,
date: d.date,
high: d.high,
low: d.low,
sortable: true,
resizeable: true
});
});
dataAvailable()
// console.log(arr); //returns arr with data
});