Javascript does not exit for loop when return statement is called

问题: While iterating through the for loop inside my function, even after the return statement is reached, the loop proceeds infinitely. At this point, j is greater than lister...

问题:

While iterating through the for loop inside my function, even after the return statement is reached, the loop proceeds infinitely.

At this point, j is greater than lister.length. It exits the for loop and at the end of function jumps back to the for loop in a seemingly endless circuit.

This behaviour doesn't make sense to me as the return statement should terminate the function.


Here is my function:

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

回答1:

may your if statement is not valid try testing by if(true){ ..code.. }

  • 发表于 2019-03-10 23:56
  • 阅读 ( 90 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除