【问题标题】:JavaScript: infinite loop, or not?JavaScript:无限循环,与否?
【发布时间】:2015-06-03 11:55:06
【问题描述】:

在我的函数中,我正在遍历一棵树,以查找节点中的特定属性。该函数被递归调用,并在找到属性或树中没有更多节点时停止。

但是,当我运行该函数时,它进入了我认为是无限循环的状态,Firefox 冻结,我必须停止该过程。然后我在函数中添加了setTimeout,以确定是什么导致了问题,但现在整个事情运行正常。如果有人对问题所在有一些了解,我将在此处发布该功能(顺便说一句,我正在使用 AngularJS 并取消选中复选框):

$scope.uncheckNode = function(nodeId, subitem){
        // Loop through each node in the sub nodes
        for (i = 0; i<subitem.length; i++){
            // If the node is found, uncheck it and break from the loop
            if (subitem[i].Id == nodeId){
                subitem[i].selected = false;
                break;
            }
            // Otherwise get the sub nodes of the subnodes
            // (an empty array if undefined)
            // Check if it has any nodes and continue with the recursion
            else{
                var subsubitem = subitem[i].Subitem || [];

                if (subsubitem.length > 0){
                   $scope.uncheckNode(nodeId, subsubitem);
                }
            }
        }
    } 

【问题讨论】:

  • 如果在子项中找不到nodeId,它将无限循环。

标签: javascript angularjs infinite-loop


【解决方案1】:

问题很可能是您使用了全局i 变量。因为您还没有声明它,所以您将成为 The Horror of Implicit Globals 的牺牲品。因此,当函数调用自身时,它将全局i 重置为0。如果从属调用返回(因为没有子项),i 将是它在从属调用中的最后一个值。如果小于调用代码中的值,您将永远循环。

要使i 成为局部变量,请将var i 添加到函数中。


您可以考虑通过在代码顶部添加"use strict" 来使用严格模式。在严格模式下,你不再有隐式全局变量,你有一个很好的明确 ReferenceError 提醒你添加声明而不是......

【讨论】:

    猜你喜欢
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多