javascript - 调用 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);
}
}
}
解决方案
可能你的 if 语句是无效的尝试测试if(true){ ..code.. }
推荐阅读
- angular - 尝试使用@angular/material,现在我的项目出现(版本控制?)错误
- sql - 在过程中填充表类型
- vba - STEP 到 STL 脚本在 478 次迭代后停止并出现运行时错误 91?
- python - 如何定义scrapy LinkExtractor 规则以跟踪所有以.css 结尾的链接?
- mongodb - MongoDB全文搜索可以得到模糊匹配的单词吗?
- regex - 正则表达式仅匹配字母数字、连字符、下划线和句点,没有重复的标点符号
- java - Rest Web 服务 404 错误 - JBoss Eclipse
- r - 一个接一个地求和行值
- c++ - 具有模板参数和类外默认参数的类的成员函数
- jquery - 将自定义列添加到 Fullcalendar Listview