javascript - 将 for 循环转换为递归函数

标签 javascript for-loop recursion

我有一个 for 循环,想将其转换为递归函数。

我有一个提示,应该为每个项目弹出并在转到列表中的下一个项目之前将其关闭。这种行为似乎不适用于普通的 for 循环。循环在提示显示之前就结束了,然后只显示一个提示,即使列表中存在多个应显示提示的项目。

(我不完全确定它是否可以与递归函数一起使用,但从我读到的内容来看,它似乎很有希望。如果我错了,那么进行转换就没有意义。)

我一直在研究其他示例,但我似乎无法理解它们到底是如何工作的。

这是我原来的循环:

for(var i = 0;i < items.get_count();i++) {
        var item = items.getItemAtIndex(i);

            //Is the item we're looking at in need of approval?
            if (item.get_item("_ModerationStatus") === 2)
            {
                //Yes, prompt for approval. (code for prompt goes here.)
                //Wait until prompt has received a response before going on next list item. 
            }

            else
            {
                //No, do nothing.
            }
        }   

我的尝试看起来有点悲伤。我不太确定从这里去哪里:

function recursiveCheckRequests(i)
        {
            if (i < items.get_count())
            {
                function checkRequest(items, )
                //???
            }

        }
        recursiveCheckRequests(0);

最佳答案

您必须从函数内部调用该函数。

function recursiveCheckRequests(i) {
    var item = items.getItemAtIndex(i);
    //Is the item we're looking at in need of approval?
    if (item.get_item("_ModerationStatus") === 2) {
        //Yes, prompt for approval. (code for prompt goes here.)
        //Wait until prompt has received a response before going on next list item.
    }
    if (i + 1 < items.get_count()) {
        recursiveCheckRequests(i + 1);
    }
}
recursiveCheckRequests(0);

关于javascript - 将 for 循环转换为递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24330654/

相关文章:

javascript - 随机循环按计划工作,但在几次调用后卡在特定的随机数上

mysql - 如何在 SQL 中进行递归查询?

javascript - Angular 不解析 IE9 和 10 中 style 属性中的模板 {{value}}

javascript - 内容超出div高度后扩展div的宽度

php - 循环嵌套,我得到一个空白页 (php)

Python数据框: Create New Column Based on Values in a String Column and a Float Column

python - Tkinter 使用菜单栏命令无意递归...原因?

f# - F# 中的显式类型递归

javascript - 如何使用流解析缓冲区中的行?

javascript - 没有类的 jQuery 翻转容器