这是我在脚本标记
中的html文件中的代码var links;
d3.json("sample.json",function(json){links=json;});
var inputlinks=[];
var nodes = {};
inputlinks.push(links);
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source, type:link.type});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target, type:link.typeKBP});
});
在此代码中出现错误
TypeError: links is undefined
links.forEach(function(link)
答案 0 :(得分:2)
正如评论中所指出的,d3.json
是一个异步调用。这意味着处理函数中的代码将在返回时运行,而不是立即运行。 之后的代码会立即运行。
要修复,请将其余代码移到处理函数中:
d3.json("sample.json",function(json){
var links = json;
var inputlinks=[];
var nodes = {};
inputlinks.push(links);
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source, type:link.type});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target, type:link.typeKBP});
});
});
答案 1 :(得分:2)
根据您提供的信息,我只能猜测您应该在回调中包含所有loginc:
var links;
d3.json("sample.json",function(json){
links=json;
var inputlinks=[];
var nodes = {};
inputlinks.push(links);
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source, type:link.type});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target, type:link.typeKBP});
});
});