首页 > 解决方案 > 调用 return 语句时,Javascript 不会退出 for 循环

问题描述

在我的函数内部迭代for循环时,即使在return到达语句之后,循环也会无限进行。

此时,j大于lister.length。它退出for循环并在函数结束时以看似无穷无尽的循环跳回for循环。

这种行为对我来说没有意义,因为return语句应该终止函数。


这是我的功能:

function permutationLoop(originalArray, listOfPermutations) {

    // generates a permutation(Shuffle),and makes sure it is not already in the list of Perms
    var lister = generatingPerms(originalArray, listOfPermutations);

    //adds the permutation to the list
    listOfPermutations.push(lister);

    var tester = true;

    //This for loop looks through the new permutation to see if it is in-order.
    for (var j = 0; j < lister.length; j++) {

        //This if statement checks to see as we iterate if it is in order
        if (lister[j] > lister[j + 1]) {
            tester = false;
        }

        if (j == (lister.length - 1) && tester == true) {
            //Return the permutation number that found the ordered array.

            return listOfPermutations.length;
            //THIS IS NOT EXITING THE LOOP
        }

        if (j == lister.length - 1 && tester == false) {
            permutationLoop(originalArray, listOfPermutations);
        }
    }
}

标签: javascriptfunctionfor-loopreturninfinite-loop

解决方案


可能你的 if 语句是无效的尝试测试if(true){ ..code.. }


推荐阅读