cor*_*zza 1 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
*/
Run Code Online (Sandbox Code Playgroud)
但是,它只是这样:
000
000
000
001
return
Run Code Online (Sandbox Code Playgroud)
谁能告诉我为什么会这样?我做错了什么?
你忘了宣布"pos" var.
var circ = function(cS)
{
for (var pos = 0; pos <= 1; pos ++)
{
rs[cS] = pos;
if (cS + 1 < rs.length)
circ(cS + 1);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
因为你忘了var,"pos"是全局性的,所以这种反复调用会扰乱父环境.
我无法保证这是唯一的问题.例如,在写入的函数中,它可以遍历所有排列,但它不显示它们或将它们复制到任何地方,因此最终结果将是[1, 1, 1].