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

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

问题描述

我使用它来解析一个csv文件并创建一个数组数据,如d3 docs中指定:

  d3.csv (afile.csv,function(data){
data.forEach(function(d){
d.date = formatDate.parse(d.date);
d.price =但是,如果在这个方法之后,我尝试使用这个方法来创建一个新的方法。调用 data [0] 它说它是未定义的,这是因为 data 是一个引用,一次 d3.csv()超出范围被销毁?如果是这样的情况下,我可以克服这个,我需要引用数据 d3.csv

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

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

如果你想使用d3.csv加载的数据,你需要把回调函数中的代码(第三是上面的):

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

function doSomethingWithRows(rows){
//使用行执行操作
}

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

  var rows; 

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

function doSomethingWithRows(){
//用行执行某些操作
}

如果愿意,你也可以将加载的数据显式地分配给窗口对象,而不是声明一个变量,然后管理两个不同的名称:

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

function doSomethingWithRows(){
//用行执行某些操作
}


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;
});

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 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();

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
}

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天全站免登陆