简体   繁体   English

我需要帮助来理解这个 function

[英]I need help to understand this function

This code from ( Eloquent Javascript chapter 7 3rd edition ).此代码来自( Eloquent Javascript第 7 章第 3 版)。

A mail-delivery robot picking up and dropping off parcels.一个邮件投递机器人拾取和投递包裹。 The village consists of 11 places with 14 roads between them.该村由11个地方组成,它们之间有14条道路。 It can be described with this array of roads.可以用这一系列的道路来描述。

const roads = [
  "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",
];

// Okay I was trying to understand this function below but I couldn't, specially the for loop

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);

What does the for loop do? for循环有什么作用?

edges.map() calls a function on each element of the edges array (which corresponds to the global roads array because it's the argument to the function). edges.map()edges数组的每个元素上调用 function(对应于全局roads数组,因为它是函数的参数)。 It collects all the return values into an array and returns this.它将所有返回值收集到一个数组中并返回它。

The function it calls uses .split('-') to split each string into an array, using - as the delimiter.它调用的 function 使用.split('-')将每个字符串拆分为一个数组,使用-作为分隔符。 For example, the string "Alice's House-Bob's House" becomes ["Alice's House", "Bob's House"] .例如,字符串"Alice's House-Bob's House"变为["Alice's House", "Bob's House"] So together with .map() , this returns an array of nested arrays:因此,与.map()一起,这将返回一个嵌套的 arrays 数组:

[
    ["Alice's House", "Bob's House"],
    ["Alice's House", "Cabin"],
    ...
]

The for-of loop then iterates over the elements of this array.然后for-of循环遍历这个数组的元素。 Using the destructuring pattern [from, to] as the iteration variable assigns the variables from and to from the corresponding elements of each nested array.使用解构模式[from, to]作为迭代变量,从每个嵌套数组的相应元素中分配变量fromto So on the first iteration from = "Alice's House" and to = "Bob's House" .所以在第一次迭代from = "Alice's House"to = "Bob's House" On the second iteration from = "Alice's House" and to = "Cabin" .from = "Alice's House" to = "Cabin"的第二次迭代中。

The loop body then calls addEdge() with these variables to create graph edges that connect the two nodes in each direction.然后循环体使用这些变量调用addEdge()来创建连接每个方向上的两个节点的图边。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM