简体   繁体   English

Javascript:递归+ for循环+作用域

[英]Javascript: recursion + for loop + scope

For the past few days I have tried to solve this problem, but up until now I have not been able to find a solution. 在过去的几天里,我一直试图解决此问题,但是直到现在,我仍无法找到解决方案。

The code below recursively finds paths on a graph. 下面的代码递归地找到图上的路径。 Instead of outputting nodePath's with four nodes, it seems to output 'one nodePath' with a newly added node from every cycle (resulting in path's from 1 to 200+ nodes incrementally). 似乎没有输出带有四个节点的nodePath,而是从每个周期输出带有一个新添加的节点的“一个nodePath”(导致路径从1到200+个节点递增)。 The recursive path call does not seem to make a fresh 'nodePath', however it does with neighbors[node_nw] and depth. 递归路径调用似乎并没有创建一个新的“ nodePath”,但是它使用了neighbors [node_nw]和depth。

var startNode = s.graph.nodes('n0');
var emptyNodeRoute = [];
path(startNode, 0, emptyNodeRoute);

function path (node, depth, nodePath) {
  nodePath.push(node);
  if (depth == 3) {
    printPath (nodePath);
  } else {
    depth ++;
    var neighbors = s.graph.neighbors(node.id);
    for (var node_nw in neighbors) {
      (function() {   
        path (neighbors[node_nw], depth, nodePath);
      }());
    }
  }
}

//prints node route
function printPath (nodePath) {
  var str = '';
  for(var k = 0; k < nodePath.length;  k++) {
    str = str.concat(' ', nodePath[k].label);
  }
  console.log ('nodePath: ' + str);
}

I guess it has to do with the specificity's of javascript regarding (no) block scoping, closures and recursion? 我猜想这与javascript关于(否)块作用域,闭包和递归有关的特殊性有关吗? Or maybe something small I am overlooking? 还是我忽略的小东西? I have referenced several resources (amongst http://zef.me/2843/javascript-the-scope-pitfall ) and topics on this site but none of them got me into solving this problem. 我已经参考了本网站上的一些资源(在http://zef.me/2843/javascript-the-scope-pitfall中 )和主题,但是没有一个使我能够解决这个问题。

Any help would be greatly appreciated! 任何帮助将不胜感激!

This is not an scoping, closure or recursion problem, but a reference problem . 这不是范围,闭合或递归问题,而是参考问题

You always call the path function with the same nodePath reference. 您始终使用相同的nodePath引用调用path函数。 Copy the nodePath variable and everything works as expected. 复制nodePath变量,一切将按预期工作。

Here is what you have to change: 这是您必须更改的内容:

for (var node_nw in neighbors) {
   // the method slice makes a copy of the array
   path (neighbors[node_nw], depth, nodePath.slice());
}

Have a look at the working jsFiddle demo . 看一下正在工作的jsFiddle演示

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

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