有人可以帮助我理解此代码吗?

时间:2018-07-26 18:25:04

标签: javascript arrays object

Here's the full project

我不了解graph [from]的工作原理,是否在'from'位置检查数组中的值?还是“来自”对象的属性名称?我在终端中都尝试过,当from是一个数字时,使用from作为属性名是可行的。将其用作数组索引会给我一个错误,指出“来自未定义”。 还有graph [from] .push(to)。如何运作?

function buildGraph(edges) {
  let graph = Object.create(null);

  function addEdge(from, to) {
    if (graph[from] == null) {
      graph[from] = [to];
    } else {
      graph[from].push(to);
    }
  }
  for (let[from, to] of edges.map(r = > r.split("-"))) {
    addEdge(from, to);
    addEdge(to, from);
  }
  return graph;
}
const roadGraph = buildGraph(roads);

2 个答案:

答案 0 :(得分:1)

您有一条道路列表,定义为list os字符串对,并以'-'相连,例如"Alice's House-Bob's House"是连接爱丽丝和鲍伯故居的道路。

然后,每条道路都由2条边线合并而成:爱丽丝屋(Alice House)和鲍勃屋(Bob house)(您用split('_')将道路分割为边)。

现在,您创建道路图,这里称为graph。对于每条道路,从点A-> B和点B-> A添加2条边线。

addEdge(from, to);
addEdge(to, from);

因为您可以使用同一条道路双向行驶。

每个addEdge调用都会检查图中是否已经注册了边from。 但我认为它应该像这样:

 function addEdge(from, to) {
    if (!graph[from]) { // if object 'from' is not yet register, add an empty array to from key
      graph[from] = [];
    }
    graph[from].push(to); // add edge 'to, to mapping of 'from'
  }

因此最终您将构建一张地图,看起来像这样:

graph = {
   'Alice house': ['Bob house', 'Post office'],
   'Post office': ['Alice house'],
   'Bob house': ['Alice house']
}

答案 1 :(得分:0)

点击您喜欢的浏览器的开发工具。在其中输入:

let roadsX = [
  "Alice's House-Bob's House",   "Alice's House-Cabin",
  "Alice's House-Post Office",   "Bob's House-Town Hall",
  "Daria's House-Ernie's House", "Daria's House-Town Hall",
  "Ernie's House-Grete's House", "Grete's House-Farm",
  "Grete's House-Shop",          "Marketplace-Farm",
  "Marketplace-Post Office",     "Marketplace-Shop",
  "Marketplace-Town Hall",       "Shop-Town Hall"
];

function buildGraph(edges) {
  let graph = Object.create(null);
  function addEdge(from, to) {
    if (graph[from] == null) {
      graph[from] = [to];
    } else {
      graph[from].push(to);
    }
  }
  for (let [from, to] of edges.map(r => r.split("-"))) {
    addEdge(from, to);
    addEdge(to, from);
  }
  return graph;
}

let roadGraphX = buildGraph(roads);

console.log(roadGraphX);

您将看到函数的作用。