Javascript 在调用 return 语句时不退出 for 循环
Javascript does not exit for loop when return statement is called
在我的函数中遍历 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.. }
进行测试
在我的函数中遍历 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.. }