(无限?)javascript代码中的循环 [英] (infinite?) loop in javascript code

查看:21
本文介绍了(无限?)javascript代码中的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 JavaScript 代码可以在网站上显示"XML:

I have the following JavaScript code to "display" XML on a website:

function createChild(node,tabindex){

    var child = node.childNodes;

    var r = '';

    var tabs = '';

    for(i=0;i<tabindex;i++){

        tabs += "\t";

    };

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

        if(child[i].nodeType == 1){

            r += tabs+"&lt;"+child[i].nodeName+"&gt;\n";

            if(child[i].hasChildNodes()){ r += createChild(child[i],1); }; // here is where it fails!

            r += tabs+"&lt;/"+child[i].nodeName+"&gt;\n";

        }

    }

    return r;

 };


function parseXML(xml){

    var doc = new DOMParser().parseFromString(xml,'application/xml');

    var node = doc.getElementsByTagName('*')[0];

    var r = '';

    r += "&lt;<span class=\"highlight highlight-blue\">"+node.nodeName+"</span>&gt;\n";

    if(node.hasChildNodes()){ r += createChild(node,1); };

    r += "&lt;<span class=\"highlight highlight-blue\">/"+node.nodeName+"</span>&gt;\n";

    $('.viewer').html(r);
};

这在 XML 上运行良好,如下所示:

This works fine on XML like this:

<properties>
    <property></property>
</properties>

但是当有不止一个孩子的时候就不行了:

But it fails to work when there is more than one child like this:

<properties>
    <property>
        <value></value>
    </property>
</properties>

代码一直运行,直到我的浏览器崩溃.我认为其中存在无限循环,但我不确定.有人给我提示吗?

The code keeps running until my browser crashes. I think there is an infinite loop in it, but I'm not sure. Does anyone have a tip for me?

推荐答案

这就是为什么你应该总是声明你的变量:

This is why you should always declare your variables:

// declare 'i'
for(var i = 0; i < tabindex ; i++){
  tabs += "\t";
};

如果没有在函数作用域中声明i,它将是全局的,从而干扰递归函数调用中的for循环:

If you don't declare i in the function scope, it will be global, thus interfering with the for loop in a recursive function call:

  1. i 变量在第一次函数调用中设置为 0.

  1. The i variable is set to 0 in the first function call.

函数调用自身.

i 变量设置为 0.

函数返回.

i 现在又是 0,所以第一帧中的循环将永远运行.

i is now 0 again, so the loop in the first frame will run forever.

所以在 createChild 函数的某个地方,你必须声明 i,要么在第一个循环之前,要么在第一个循环中.您也可以使用 let.

So somewhere in the createChild function, you have to declare i, either before the first loop or in the first loop. You can also use let.

这篇关于(无限?)javascript代码中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆