为什么JS中的这种递归算法不起作用?

时间:2011-12-26 22:48:27

标签: javascript recursion

我做了这个简单的算法,但Chrome表现得很奇怪,几乎就像递归的函数一样不返回...算法的任务是循环通过rs数组的所有可能性,它有三个元素,可以是0或1。

//rs is the list of all variables that can be 0 or 1
//cS, or currentStack is the variable that s

rs = [0, 0, 0];

circ = function(cS)
{
     for (pos = 0; pos <= 1; pos ++)
     {
          rs[cS] = pos;
          if (cS + 1 < rs.length)
               circ(cS + 1);
     }
     return 0;                    
}

circ(0); //this should cycle trough all the possibilities of the rs array, it should look like this:
/*
000 - first element of rs, not last, so continue to the next
000 - second element of rs, not last, so continue to the next
000 - third element of rs, last, so continue with the for loop
001 - the for loop ends, return to the second element
011 - second element of rs, not last, so continue to the next
010 - third element of rs, last, so continue with the for loop
011 - the for loop ends, return to the first element
111 - first element of rs, not last, so continue to the next
101 - second element of rs, not last, so continue to the next
100 - third element of rs, last, so continue with the for loop
101 - the for loop ends, return to the second element
111 - second element of rs, not last, so continue to the next
110 - third element of rs, last, so continue with the for loop
111 - the for loop ends, return to the second element
111 - the for loop ends, return to the first element
111 - return
*/

然而,它只是这样:

000
000
000
001
return

谁能告诉我为什么会这样?我做错了什么?

1 个答案:

答案 0 :(得分:6)

您忘记使用var声明“pos”。

var circ = function(cS)
{
     for (var pos = 0; pos <= 1; pos ++)
     {
          rs[cS] = pos;
          if (cS + 1 < rs.length)
               circ(cS + 1);
     }
     return 0;                    
}

因为你忘记了var,所以“pos”是全局的,所以这种反复调用会扰乱父环境。

我不能保证这是唯一的问题。例如,在编写的函数中,它可以遍历所有排列,但它不显示它们或将它们复制到任何地方,因此最终结果将只是[1, 1, 1]