简体   繁体   English

(无限?)JavaScript代码循环

[英](infinite?) loop in javascript code

I have the following JavaScript code to "display" XML on a website: 我有以下JavaScript代码可以在网站上“显示” XML:

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);
};

This works fine on XML like this: 像这样在XML上运行良好:

<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";
};

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: 如果未在函数范围内声明i ,它将是全局的,因此会在递归函数调用中干扰for循环:

  1. The i variable is set to 0 in the first function call. 在第一个函数调用中将i变量设置为0

  2. The function is calls itself. 函数本身就是调用。

  3. The i variable is set to 0 . i变量设置为0

  4. The function returns. 函数返回。

  5. i is now 0 again, so the loop in the first frame will run forever. i现在再次为0 ,因此第一帧中的循环将永远运行。

So somewhere in the createChild function, you have to declare i , either before the first loop or in the first loop. 因此,在createChild函数中的某个位置,您必须在第一个循环之前或在第一个循环中声明i You can also use let . 您也可以使用let

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM