【问题标题】:Javascript does not exit for loop when return statement is called调用 return 语句时,Javascript 不会退出 for 循环
【发布时间】:2019-07-31 03:47:27
【问题描述】:

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

【问题讨论】:

  • 你能否举一个你调用函数的输入示例(希望也有generatingPerms,因为它在你正在使用的代码中),最好是在实时 sn-p 中,这样我们就可以自己查看函数是如何运行的并尝试调试它?
  • 什么是generatingPerms()
  • 问题是:if (lister[j] &gt; lister[j+1]);如果j 是最后一个元素,j+1 将是未定义的,因此小于最后一个元素,因此tester 将设置为 false,并且在最后一个元素上具有返回的 IF 条件始终为 false。

标签: javascript function for-loop return infinite-loop


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 2014-08-28
    相关资源
    最近更新 更多