csv 到 d3.js 中的数组 [英] csv to array in d3.js

查看:37
本文介绍了csv 到 d3.js 中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用它来解析 csv 文件并创建 d3 文档中指定的数组数据:

I am using this to parse a csv file and create an array data as specified in d3 docs:

d3.csv("afile.csv", function(data) {
    data.forEach(function(d) {
    d.date = formatDate.parse(d.date);
    d.price = +d.price;
});

然而,如果在这个方法之后我尝试调用 data[0] 它说它是未定义的.这是因为 data 是一个引用并且一旦 d3.csv() 超出范围就会被销毁吗?如果是这种情况,我该如何克服.我需要从 d3.csv()

However, if after this method I try to call data[0] it says it is undefined. Is this because data is a reference and once d3.csv() is out of scope is destroyed? If this is the case how can I overcome this. I need to reference data out of d3.csv()

推荐答案

d3.csv 是一种异步方法.这意味着回调函数内部的代码在数据加载时运行,但是当数据尚不可用时,回调函数之后和外部的代码将在请求发出后立即运行.换句话说:

d3.csv is an asynchronous method. This means that code inside the callback function is run when the data is loaded, but code after and outside the callback function will be run immediately after the request is made, when the data is not yet available. In other words:

first();
d3.csv("path/to/file.csv", function(rows) {
  third();
});
second();

如果你想使用 d3.csv 加载的数据,你要么需要将该代码放在回调函数中(上面的 third 是):

If you want to use the data that is loaded by d3.csv, you either need to put that code inside the callback function (where third is, above):

d3.csv("path/to/file.csv", function(rows) {
  doSomethingWithRows(rows);
});

function doSomethingWithRows(rows) {
  // do something with rows
}

或者,您可以将其保存为窗口中的全局变量,以便稍后参考:

Or, you might save it as a global variable on the window that you can then refer to later:

var rows;

d3.csv("path/to/file.csv", function(loadedRows) {
  rows = loadedRows;
  doSomethingWithRows();
});

function doSomethingWithRows() {
  // do something with rows
}

如果需要,还可以将加载的数据显式分配给 window 对象,而不是声明一个变量然后管理两个不同的名称:

If you want, you can also assign the loaded data explicitly to the window object, rather than declaring a variable and then managing two different names:

d3.csv("path/to/file.csv", function(rows) {
  window.rows = rows;
  doSomethingWithRows();
});

function doSomethingWithRows() {
  // do something with rows
}

这篇关于csv 到 d3.js 中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆