D3 csv返回行

hol*_*lys 2 javascript csv d3.js

这是来自d3csv API文档:

d3.csv("path/to/file.csv")
    .row(function(d) { return {key: d.key, value: +d.value}; })
    .get(function(error, rows) { console.log(rows); });
Run Code Online (Sandbox Code Playgroud)

我怎么能把它传递rows给一段var data时间而不仅仅是console.log它.我只想要来自csv的数据,但我不熟悉JavaScript.

mee*_*mit 16

这里的答案仅适用于d3 v4及以下版本.从d3 v5开始,此方法已更改.有关最新解决方案,请参阅此答案.

请记住,d3.csv()返回任何数据是不可能的,因为数据必须首先加载.这就是我们使用回调函数的原因,这些函数在加载数据后会被调用(您可以通过研究"异步javascript"来了解更多信息).

您仍然可以将加载的数据分配给变量,但必须记住隐含异步函数.

// 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
}
Run Code Online (Sandbox Code Playgroud)

关键是在加载和解析CSV之前,您无法绘制任何内容.所以无论如何,你的绘图代码都必须存在于从d3.csv回调调用的函数中.

可以构造代码,使得您永远不需要分配rows给变量(您只需要传入rows绘制数据的函数).