问题描述
这是来自 d3
csv API文件:
This is from d3
csv API document:
d3.csv("path/to/file.csv")
.row(function(d) { return {key: d.key, value: +d.value}; })
.get(function(error, rows) { console.log(rows); });
如何将行
var data
,而不只是 console.log
。我只想从csv的数据,但我不熟悉JavaScript。
How can I pass the rows
to a var data
while not just console.log
it. I just want the data from csv but I am not familiar with JavaScript.
推荐答案
请记住,不可能有 d3.csv()
返回任何数据,因为数据必须首先加载。这就是为什么我们使用回调函数,一旦数据加载就可以调用(通过研究异步javascript可以了解更多信息)。
Keep in mind that it's impossible to have d3.csv()
return any data, because the data has to first load. That's why we use callback functions, which get invoked once the data is loaded (you can learn more by researching about "asynchronous javascript").
数据到一个变量,但你必须记住涉及的异步函数。
You still can assign your loaded data to a variable, but you have to keep in mind the implication asynchronous functions.
// This will be assigned to rows, once the data is ready.
var myData = null;
d3.csv("path/to/file.csv")
.row(function(d) { return {key: d.key, value: +d.value}; })
.get(function(error, rows) {
console.log(rows);
myData = rows;// Now you can assign it
myDataIsReady()// Now you can draw it
});
// IMPORTANT NOTE! Here myData is still null
console.log(myData);// will trace null
function myDataIsReady() {
console.log(myData);// will trace the data that was loaded
// Here you can draw your visualization
}
关键是你不能绘制任何东西,直到你的CSV加载和解析。因此,不管是什么,你的绘图代码必须住在从 d3.csv
回调中调用的一些函数中。
The point is that you can't draw anything until your CSV is loaded and parsed. So no matter what, your drawing code has to live inside some function that gets called from the d3.csv
callback.
可以构造你的代码,这样你永远不需要分配行
到一个变量(你只需要传递 rows
进入绘制数据的函数)。
It's possible to structure your code such that you'd never need to assign rows
to a variable (you'd just pass rows
into the function that draws the data).
这篇关于D3 csv返回行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!