为什么这个 DOM DFS 算法不起作用?

Why this DOM DFS algorithm doesn't work?

我尝试了下面的算法对 DOM 树进行 DFS,但它不起作用!它可以只检查 DOM 树中的第一条路径。为什么?!

function DFS(P) // (ScanRegion, Elem, MCF)
{
    P.Elem.setAttribute("Checked", "1");

    Children = P.Elem.querySelectorAll("*");

    for(I = 0, L = Children.length; I < L; I++)
        DFS
        (
            {
                ScanRegion : P.ScanRegion,
                Elem       : Children[I] ,
                MCF        : P.MCF
            }
        );

    return;
}

DFS
(
    {
        ScanRegion : document.body,
        Elem       : document.body,
        MCF        : "Not important in this question :D"
    }
);

经过几天的调试,我终于找到了问题所在。我尝试了下面的代码并了解到在函数丰富到 DOM 树的第一个叶子并且浏览器运行递归函数的第一个 'return' 之后,父级的 'L' 变量函数失去其值并更改为“0”。我猜这是因为 JS 中的变量范围问题,因为如您所知,子函数的 'L' 为“0”(因为叶子没有子 :D),我认为它会影响父函数。

这是我试过的调试代码:

function DFS(P) // (ScanRegion, Elem, MCF)
{
    P.Elem.setAttribute("Checked", "1");

    Children = P.Elem.querySelectorAll("*");

    L = Children.length; alert(L); // * New

    for(I = 0; I < L; I++)
        DFS
        (
            {
                ScanRegion : P.ScanRegion,
                Elem       : Children[I] ,
                MCF        : P.MCF
            }
        );

    alert(L); // * New

    return;
}

DFS
(
    {
        ScanRegion : document.body,
        Elem       : document.body,
        MCF        : "Not important in this question :D"
    }
);

如果有人知道这个问题或有真正的代码,我将不胜感激:)

var 声明你的局部变量!!就目前而言,I 全局 。与 L 相同。因此,递归调用打乱了父级的迭代。

添加

var I, L;

到函数的顶部。 (也可以考虑使用小写字母作为变量名;它在 JavaScript 代码中更常见。)