我似乎无法深究这个问题。我有以下Javascript代码:
for(var i=0; i<links1.length; ++i) {
console.log(links1[i]);
}
console.log(links1);
for循环的输出如下:
Object {source: 2, target: 16}
Object {source: 32, target: 15}
Object {source: 32, target: 31}
Object {source: 16, target: 104}
Object {source: 104, target: 32}
...
虽然console.log(links1)行产生:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
source: Object
target: Object
__proto__: Object
1: Object
source: undefined
target: Object
__proto__: Object
2: Object
source: 32
target: 31
__proto__: Object
3: Object
source: 16
target: 104
__proto__: Object
4: Object
source: 104
target: 32
__proto__: Object
...
为什么在世界上我得到前两个元素的不同值?
后台没有进行AJAX调用,调用的d3.js方法是parseRows(不应该是异步)。
如果相关,代码的上下文是:
function draw_graph(nodes1, links1) {
var width = 500;
var height = 500;
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
console.log('tu');
for(var i=0; i<links1.length; ++i) {
console.log(links1[i]);
}
console.log(links1);
console.log(nodes1);
force
.nodes(nodes1)
.links(links1)
.start();
...
}
d3.text("test1.txt", function(text) {
var nodes = [];
rows = d3.dsv(" ", "text/plain").parseRows(text);
for(var i=0; i<rows.length; ++i) {
newEl = {name:+rows[i][0], value:+rows[i][0]};
nodes.push(newEl);
}
d3.text("test2.txt", function(text) {
var links = [];
rows = d3.dsv(" ", "text/plain").parseRows(text);
for(var i=0; i<rows.length; ++i) {
newEl = {source:+(rows[i][0]), target:+(rows[i][1])};
links.push(newEl);
}
draw_graph(nodes, links);
});
});
......死于
force
.nodes(nodes1)
.links(links1)
.start();
使用:
Uncaught TypeError: Cannot read property 'weight' of undefined d3.js:6244
force.start d3.js:6244
draw_graph test.php:58
(anonymous function) test.php:113
(anonymous function) d3.js:1931
(anonymous function) d3.js:1916
event d3.js:434
respond
如果有人知道我做错了什么,请告诉我。
谢谢!