我目前正在尝试使用d3.js'来构建一个非常基本的图形。力布局。我遇到了错误:"无法读取属性'推送'未定义"当我试图运行我的代码时,希望有人能告诉我出了什么问题。
错误发生在d3.js版本3.5.6中的第6388行,该行为:
neighbors[o.source.index].push(o.target);
它遇到的问题是对象o.source不包含名为index的属性,即使该属性应该先前在force.start()函数中设置,如下面的代码所示: / p>
force.start = function() {
var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o;
for (i = 0; i < n; ++i) {
(o = nodes[i]).index = i;
o.weight = 0;
}
for (i = 0; i < m; ++i) {
o = links[i];
if (typeof o.source == "number") o.source = nodes[o.source];
if (typeof o.target == "number") o.target = nodes[o.target];
++o.source.weight;
++o.target.weight;
}
for (i = 0; i < n; ++i) {
o = nodes[i];
if (isNaN(o.x)) o.x = position("x", w);
if (isNaN(o.y)) o.y = position("y", h);
if (isNaN(o.px)) o.px = o.x;
if (isNaN(o.py)) o.py = o.y;
}
distances = [];
if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance;
strengths = [];
if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength;
charges = [];
if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge;
function position(dimension, size) {
if (!neighbors) {
neighbors = new Array(n);
for (j = 0; j < n; ++j) {
neighbors[j] = [];
}
for (j = 0; j < m; ++j) {
var o = links[j];
neighbors[o.source.index].push(o.target);
neighbors[o.target.index].push(o.source);
}
}
var candidates = neighbors[i], j = -1, l = candidates.length, x;
while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x;
return Math.random() * size;
}
return force.resume();
};
从我已经能够在这个主题上找到的,似乎问题可能在于我的节点和链接数组的格式。我似乎无法找到问题,所以也许你可以。我的nodes数组包含如下所示的对象:
{
games: [...],
id: 'some id'
}
我的链接对象如下所示:
{
source: nodeObject,
target: nodeObject,
weight: number
}
我设置力布局的代码如下:
var force = d3.layout.force().charge(-1000)
.size([500, 500])
.nodes(nodes)
.links(edges)
.linkStrength(function(d) {
return weightScale(d.weight);
})
.on('tick', forceTick);
d3.select('svg').selectAll('line.link')
.data(edges, function(d) {
return d.source.id + '-' + d.target.id;
})
.enter()
.append('line')
.attr('class', 'link')
.style('stroke', 'black')
.style('opacity', 0.5)
.style('stroke-width', function(d) {
return d.weight;
});
var nodeEnter = d3.select('svg').selectAll('g.node')
.data(nodes, function(d) {
return d.id;
})
.enter()
.append('g')
.attr('class', 'node');
任何人都可以帮我弄清楚为什么我收到上面提到的错误?非常感谢你的时间。