从图中的链接解析节点

问题描述 投票:1回答:1

我有一个带有链接数组中指定边的图形。下面的函数是从链接解析节点,但我不太明白如何。 OR语句中第一个子句的目的是什么,即link.source = nodes [link.source]?

var links=[{source:"A", target:"B"}, {source:"B", target:"C"}, {source:"D", target:"E"}, {source:"E", target:"C"}];

var nodes=[];

links.forEach(function(link){
    link.source = nodes[link.source] || (nodes[link.source]={eid:link.source});
    link.target = nodes[link.target] || (nodes[link.target]={eid:link.target});
});

我是JavaScript的新手,在经过多次调试后,我仍然迷失方向。

javascript d3.js
1个回答
1
投票

看起来你试图通过迭代你的nodes数组来创建一个links对象,但是你将nodes变量设置为一个空数组。相反,您应该将其设置为空对象:nodes = {}。将links.forEach()包装在一个函数中会更有意义,因为看起来好像是多次调用它并返回nodes对象值(如果已创建),或者如果它尚不存在则创建它。尝试示例(添加日志记录,以便您可以看到代码的结果):

const links = [
  {source: "A", target: "B"},
  {source: "B", target: "C"},
  {source: "D", target: "E"},
  {source: "E", target: "C"}
  ];
    
const nodes = {};  
links.forEach((link) => {
  link.source = nodes[link.source] || (nodes[link.source] = {
    eid: link.source
  });
  link.target = nodes[link.target] || (nodes[link.target] = {
    eid: link.target
  });
  console.log(link.source);
  console.log(link.target);
});
    
console.log(nodes);
© www.soinside.com 2019 - 2024. All rights reserved.