调用 return 语句时,Javascript 不会退出 for 循环

标签 javascript function for-loop return infinite-loop

在我的函数中遍历 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);
        }
    }
}

最佳答案

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

进行测试

关于调用 return 语句时,Javascript 不会退出 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55074596/

相关文章:

MySQL:创建返回数组的函数

c++ - 如何将 vector 传递给函数?

python - 从另一个 DataFrame 的列中的 JSON URL 生成 Dataframe

Java 缓冲编写器不会写入所有数据

javascript - 使用 jQuery 单击时切换 .html 文本

javascript - TamperMonkey 可以创建书签吗?

vb.net - "obj.X"VB.net 的术语正确吗?

python - 将多行 for 循环更改为单行 For 循环

javascript - 为什么类和函数在 Javascript 中的行为不同?

javascript - JQuery get 方法似乎不起作用