递归函数调用如何在循环中工作?
我有一个函数,其中有一个调用该函数的循环。
function displayItem(item, isChild)
{
if (isChild)
{
writeOutput('<li>' & item.name & '</li>');
}
else
{
writeOutput('<li>' & item.name);
}
try
{
if (item.hasChild)
{
writeOutput('<ul>');
numberOfItems = item.numChildren;
for (x=1;x LT numberOfItems;x++)
{
displayItem(item.child[x], true);
}
writeOutput('</ul>');
}
}
catch(Exception e){}
writeOutput('</li>');
}
执行该函数后,循环将从该执行中的 x 值继续,而不是从之前中断的位置继续。
例如:x 是 3。displayItem 传递“item.child[3]”和 true。它执行该函数,进入循环,执行循环直到 x = 4,然后退出循环。函数结束并(根据我的理解)返回到 x 应该为 3 的点。它不是从 3 中选取,加一(使其成为 4),然后再次执行循环,而是从 4 中选取(值来自“内部”递归地称为循环)。
我知道这听起来不连贯,但我想不出任何其他方式来解释它。
我是否做错了什么,或者这只是生活的事实,我必须解决这个问题?
更新: 仔细观察后,似乎最早的循环提前退出了。使用局部变量“x”解决了计数问题,但如果查看前面的示例,循环将在 4 处退出。它会在条件满足之前离开。有什么想法吗?
I have a function, in which there is a loop which calls up the function.
function displayItem(item, isChild)
{
if (isChild)
{
writeOutput('<li>' & item.name & '</li>');
}
else
{
writeOutput('<li>' & item.name);
}
try
{
if (item.hasChild)
{
writeOutput('<ul>');
numberOfItems = item.numChildren;
for (x=1;x LT numberOfItems;x++)
{
displayItem(item.child[x], true);
}
writeOutput('</ul>');
}
}
catch(Exception e){}
writeOutput('</li>');
}
After the function is executed, the loop continues off of the value of x from that execution, rather than picking up where it left off before.
For instance: x is 3. displayItem is passed "item.child[3]" and true. It works through the function, enters the loop, performs the loop up to x = 4, then falls out of the loop. The function ends and (from what I understand) returns back to the point where x should be 3. Instead of picking up from 3, adding one (making it 4) and then performing the loop again, it picks up from 4 (the value from the "internal" recursively called loop).
I know that sounds incoherent, but I can't think of any other way to explain it.
Is there something I'm doing wrong, or is this just a fact of life and something I have to work around?
UPDATE:
After looking at it more, it appears as though the earliest loop is exiting early. Using a local variable for 'x' fixed the counting issue, but the loop just exits at 4 if looking at the previous example. It leaves before the condition is met. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您忘记将 x 设置为该函数的本地函数。
不要使用全局变量。
像躲避瘟疫一样避开它们。
You forgot to make x local to the function.
Don't use global variables.
Avoid them like the plague.
问题是这一行:
从第二次调用返回时,该值不会更改回正确的值。 ,如果在函数自身调用时将
numberOfItems
设置为4,则在完成并返回到函数的原始实例之后,numberOfItems
仍然是4。因此 代码工作原理:
The problem is this line:
When returning from the second call, this value is not changed back to the proper value. So if
numberOfItems
is set to 4 when the function is called up by itself, after it has completed and returned to the original instance of the function,numberOfItems
is still 4.this code works:
试试这个
Try this