Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
948 views
in Technique[技术] by (71.8m points)

csv to array in d3.js

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...