d3.js 用异步函数替换 random() 数据函数

d3.js replacing random() data function with asynchronous function

我正在尝试调整 Mike Bostock 的泳道日历 http://bl.ocks.org/bunkat/1962173 并用 JSON 文件替换随机数据生成函数。

d3.json("random.json", function(data) {
//  console.log(d3.entries(data));
//var data = randomData()
var lanes = data.lanes;
var items = data.items;
var now = new Date();
.....
});

数据文件看起来像 random() 函数的输出:

{"lanes":[{"id":0,"label":"lane 0"},{"id":1,"label":"lane 1"},{"id":2,"label":"lane 2"},{"id":3,"label":"lane 3"},{"id":4,"label":"lane 4"}],"items":[{"id":0,"lane":0,"start":"2012-01-21T18:00:00.000Z","end":"2012-01-26T21:00:00.000Z","class":"past","desc":"This is a description."},{"id":1,"lane":0,"start":"2012-01-28T18:00:00.000Z","end":"2012-02-02T21:00:00.000Z","class":"past","desc":"This is a description."},{"id":2,"lane":0,"start":"2012-02-05T13:00:00.000Z","end":"2012-02-10T18:00:00.000Z","class":"past","desc":"This is a description."},{"id":3,"lane":0,"start":"2012-02-13T15:00:00.000Z","end":"2012-02-15T13:00:00.000Z","class":"past","desc":"This is a description."},{"id":4,"lane":0,"start":"2012-02-17T16:00:00.000Z","end":"2012-02-22T13:00:00.000Z","class":"past","desc":"This is a description."},{"id":5,"lane":0,"start":"2012-02-23T13:00:00.000Z","end":"2012-02-23T21:00:00.000Z","class":"past","desc":"This is a description."},{"id":6,"lane":0,"start":"2012-02-24T18:00:00.000Z","end":"2012-03-01T14:00:00.000Z","class":"past","desc":"This is a description."}

我得到的错误是:

TypeError: n.getFullYear is not a function

我相信这是因为在您的 data.items 中,您的 startend 属性是字符串而不是日期(randomData() 函数 returns 它们作为日期)。

...
var now = new Date();
items.forEach(function(d){
  d.start = new Date(d.start);
  d.end = new Date(d.end);
});
...

解析 JSON 后,您需要将日期从字符串显式转换为 Date 类型。

在给定的示例中,开始和结束变量被创建为日期对象

var dtS = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate() + randomNumber(1,5), randomNumber(8, 16), 0, 0);
var dateOffset =  randomNumber(0,7);
var dt = new Date(dtS.getFullYear(), dtS.getMonth(), dtS.getDate() + dateOffset, randomNumber(dateOffset === 0 ? dtS.getHours() + 2 : 8, 18), 0, 0);

您可以通过遍历项目并单独转换每个项目来实现此目的

items.forEach(function(d){
  d.start = new Date(d.start);
  d.end = new Date(d.end);
});

d3 有一些助手可以处理更复杂的日期字符串。您可以在这里阅读更多关于它们的信息:https://github.com/mbostock/d3/wiki/Time-Formatting#parse

var parseDate = d3.time.format.iso.parse;
items.forEach(function(d){
  d.start = parseDate (d.start);
  d.end = parseDate (d.end);
});