gpt4 book ai didi

javascript - 影响父方法变量的递归调用?

转载 作者:行者123 更新时间:2023-11-30 10:49:15 25 4
gpt4 key购买 nike

我正在构建嵌套评论。我的 AJAX 脚本获取如下注释列表并扩展它们 -

    if (xmlhttp.readyState == 4 || myOb.readyState == "complete")   {
// EVAL
var comments = eval('(' + xmlhttp.responseText + ')');

// POPULATE
var comm = "<ul>";
for(i = 0; i < comments.length; i++) {
if(comments[i].replyto == 0) {
comm = comm + expand(property, comments, i);
}
}
comm = comm + "</ul>";
// DISPLAY
document.getElementById("comments").innerHTML = comm;
}

这里,expand 函数是递归的,而且似乎引起了麻烦 -

function expand(property, comments, k)  {
var comm = "";

// PRINT MAIN COMMENTS
comm = comm + "<li>";
// print otherparent comment data

// replies
comm = comm + "<ul>";
for(i = 0; i < comments.length; i++) {
// is a reply?
if(comments[i].replyto == comments[k].id) {
comm = comm + expand(property, comments, i);
}
}
comm = comm + "</ul>";

comm = comm + "</li>";
return comm;
}

这个脚本最终只给出了第一个 comments 数组元素(及其各自的子评论)。但是如果我删除递归代码,我就不会遇到那个问题(而且,我不没有得到任何子评论)..

function expand(property, comments, k)  {
var comm = "";

// PRINT MAIN COMMENTS
comm = comm + "<li>";
// print otherparent comment data

// replies
comm = comm + "<ul>";
/*
for(i = 0; i < comments.length; i++) {
// is a reply?
if(comments[i].replyto == comments[k].id) {
comm = comm + expand(property, comments, i);
}
}
*/
comm = comm + "</ul>";

comm = comm + "</li>";
return comm;
}

我在 eval 函数中设置了两个警报,在 expand 调用之前和之后各一个:

        for(i = 0; i < comments.length; i++)    {               
if(comments[i].replyto == 0) {
alert(i);
comm = comm + expand(property, comments, i);
alert(i);
}
}

两者都给了我不同的 i 值。我做错了什么?

谢谢

最佳答案

您忘记将“i”设为局部变量:

    for(var i = 0; i < comments.length; i++)    {               

真的很重要。

关于javascript - 影响父方法变量的递归调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6445041/

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