我有一个源自 D3 V3 的脚本,我正在尝试在 V5 中重建它。
我将先查看代码,然后再解决问题。这是代码的相关部分。
var height = 570
var width = 510
var svg = d3.select("#chart").append("svg")
.attr("width", width + 160)
.attr("height", height + 90)
.append("g")
.attr("transform", "translate(" + 160 + "," + 90 + ")");
// this has a count for how many are in each group
var grpcnts = {
met: { '1960': 0, '1970': 0, '2010': 0, label: "First Met", x: 1, y: 1 },
romantic: { '1960': 0, '1970': 0, '2010': 0, label: "Romantic", x: 2, y: 1 },
lived: { '1960': 0, '1970': 0, '2010': 0, label: "Live Together", x: 3, y: 1 },
married: { '1960': 0, '1970': 0, '2010': 0, label: "Married", x: 4, y: 3 },
}
var x = d3.scaleBand()
.domain([1950, 1970, 1980, 2010])
.range([0, width]);
var y = d3.scaleBand()
.domain(d3.keys(grpcnts))
.range([height, 0]);
var sched_objs = [],
curr_index = -1;
// Load data
d3.tsv("timelines.tsv")
.then(function(data) {
data.forEach(function(d) {
var day_array = d.timeline.split(",");
var activities = [];
for (var i=0; i < day_array.length; i++) {
// Duration
if (i % 2 == 1) {
activities.push({'act': day_array[i-1], 'duration': +day_array[i]});
}
}
sched_objs.push(activities);
});
// A node for each person's schedule
var nodes = sched_objs.map(function(o,i) {
var act = o[0].act;
var init_x = x(+data[i].decade) + Math.random();
var init_y = y('met') + Math.random();
var col = "#cccccc";
grpcnts[act][data[i].decade] += 1;
return {
act: act,
radius: maxRadius,
x: init_x,
y: init_y,
decade: data[i].decade,
color: color(act),
married: false,
moves: 0,
next_move_time: o[0].duration,
sched: o
}
});
}) // end tsv
这是数据集的示例。
"decade" "timeline"
1970 "met,4,romantic,14,lived,1,married,-99"
1970 "romantic,2,married,-99"
1970 "met,9,romantic,48,married,-99"
1970 "romantic,20,married,-99"
1970 "met,2,romantic,10,married,-99"
1970 "met,13,romantic,16,married,-99"
问题是 x
和 y
字段显示为 NaN
。
我在 return 子句之前添加了 console.log
语句,并且 init_x 和 init_y 值打印出正确的数字。
我已经使用所有有效输入测试了 x()
和 y()
函数,它们返回了正确的值。我已经测试了 Math.random()
,它看起来工作得很好。
其他字段均未显示为 NaN
,这让我相信返回多个值的语法是正确的。我还尝试将 init_x
和 init_y
包装在 Number() 中。
最佳答案
不幸的是,您的代码充满了错误,以至于我们无法在不进行重大重构的情况下使其运行。
但是,只是为了回答您当前的具体问题(“NaN 来自哪里?”),这就是问题所在(pasteBin 中的第 212 行) ):
var k = 0.03 * this.alpha;
由于没有 alpha
,而是 alpha()
,所以当您使用 k
(这是 undefined
>) 后者...
o.x += (x(+o.decade) - o.x) * k * damper;
...你会得到那个漂亮的NaN
。
我想再次强调,此更改不会不会使您的代码正常工作,您还有很多其他问题需要解决。
关于javascript - 从 map 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55945883/