我正在尝试使用从外部JSON文件获取的数据进行最简单的绘图(任何类型)。我使用plotly.js
,这是d3js的扩展。
这是感兴趣的部分:
var dates = [], scores = [];
var user_json = 'https://hacker-news.firebaseio.com/v0/user/anton_tarasenko.json';
var item_json = 'https://hacker-news.firebaseio.com/v0/item/';
$.getJSON(user_json, function (user) {
$.each(user.submitted, function(i, item_id) {
$.getJSON(item_json + item_id + '.json', function(item) {
if (item.type == 'story') {
scores.push(Number(item.score));
dates.push(Number(item.time));
}
});
});
});
var data = [{
x: dates,
y: scores,
mode: 'lines+markers',
type: 'scatter'
}];
Plotly.newPlot('myDiv', data);
这将返回一个空图。但是,当我更换x: dates
使用x: [1461189218, 1460844086, ... , 1427738937]
,并y: scores
与y: [1, 154, ..., 1]
(输出console.log(dates)
和log(scores)
),它工作正常。
那么,为什么库会忽略对数组的引用呢?我认为我滥用变量,但不确定如何使用。
有任何想法吗?
您的问题与异步编程的性质有关。由于$.getJSON()
是异步的,因此在填充scores或date数组之前,实际上将执行所有后续代码。
为了使您的代码按预期工作,您可以使用方法,包括将所有剩余代码移到回调内部(并为每个项目调用图)或使用promise(并对所有数据调用一次图)。使用jQuery,您可以相对轻松地实现promise。
var user_json = 'https://hacker-news.firebaseio.com/v0/user/anton_tarasenko.json';
var item_json = 'https://hacker-news.firebaseio.com/v0/item/';
// Main
getUser()
.then(getScoresAndDates)
.then(plot);
// Declarations
function all(arrayOfPromises) {
return jQuery.when.apply(jQuery, arrayOfPromises).then(function() {
return Array.prototype.slice.call(arguments, 0);
});
}
function getUser() {
return $.getJSON(user_json);
};
function getScoresAndDates(user) {
var scoresAndDates = [];
$.each(user.submitted, function(i, item_id) {
scoresAndDates.push($.getJSON(item_json + item_id + '.json'));
});
return all(scoresAndDates);
}
function plot(result) {
scoresAndDates = result
.map(function(v){
return v[0];
})
.filter(function(v) {
return v.type == 'story';
})
var scores = scoresAndDates.map(function(v) {
return v.score
});
var dates = scoresAndDates.map(function(v) {
return v.time
});
var data = [{
x: dates,
y: scores,
mode: 'lines+markers',
type: 'scatter'
}];
Plotly.newPlot('myDiv', data);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句