gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:12:14 25 4
gpt4 key购买 nike

我做了这个简单的算法,但 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

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

最佳答案

您忘记使用 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]

关于javascript - 为什么JS中的这个递归算法不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8639674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com