简体   繁体   中英

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). The recursive path call does not seem to make a fresh 'nodePath', however it does with neighbors[node_nw] and 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? 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.

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. Copy the nodePath variable and everything works as expected.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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