【问题标题】:Javascript returns undefined when indexing into an array using a property of an object使用对象的属性对数组进行索引时,Javascript 返回未定义
【发布时间】:2021-01-22 03:46:04
【问题描述】:

我正在尝试使用数组中对象的属性检索相邻节点。我无法在节点数组中使用链接索引的属性。我想知道如何修改const a 的代码以检索值?任何帮助表示赞赏!

const gData = {
        nodes: [
          {id: "John"},
          {id: "Jack"},
          {id: "Jim"}
        ],
        links: [
          {source: "John", target: "Jim"},
          {source: "John", target: "Jack"},
          {source: "Jack", target: "Jim"}
        ]
      }
    
      // cross-link node objects
      gData.links.forEach(link => {
        
        const a = gData.nodes[link.source]; // returns undefined
        const b = gData.nodes[link.target];


        console.log("nodes in graph data ", gData.nodes)
        console.log("link", link)
        console.log("link.source", link.source)
        console.log("index into nodes  ", gData.nodes[link.source])
        
        !a.neighbors && (a.neighbors = []);
        !b.neighbors && (b.neighbors = []);
        
        a.neighbors.push(b);
        b.neighbors.push(a);
  
        !a.links && (a.links = []);
        !b.links && (b.links = []);
        
        a.links.push(link);
        b.links.push(link);
      });

以下是我 console.logged 的​​值:

【问题讨论】:

  • 第一个错误破坏了整个脚本。 link.source 不存在。你确实有一个links tho
  • 好吧,你可能有一点。我会回来的

标签: javascript d3.js graph


【解决方案1】:

问题在于 gData.nodes 是一个数组对象 - 它的键是“0”、“1”、“2”,而不是数组中条目的 id 属性值。

解决此问题的一种简单方法,即缩短或重组对象的内容,是使用 id 值作为索引键创建查找表:

  gData.index = {};
  gData.nodes.forEach( node => gData.index[node.id] = node);

然后在需要的地方从它们的id 中查找节点:

  const a = gData.index[link.source];
  const b = gData.index[link.target];

另一种解决方案可能是为gData 对象编写getNodeById 方法。

ab 的未定义值生成的语法错误应在为它们分配正确的节点值后自行解决。显然,如果在运行时可能出现错误情况,那么也应该包含错误处理代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多