[英]While-loop crashes browser
我的Javscript函数不断使浏览器崩溃。 它崩溃的次数很少,但确实有几次。 使用firebug似乎是while循环使所有内容崩溃。 有人知道吗
function generateTeams(pos = 0) {
// Array of ID's
var currentTeams = [];
// 2D array with matches and teamIds
var matches = [];
$.each($teamList, function () {
// Push integer into a new array
if (this.position >= pos) currentTeams.push(this.id);
});
// NumberOfTeams is ALWAYS even numbers, and can be divided by 2
var numberOfTeams = currentTeams.length;
var numberOfMatches = numberOfTeams / 2;
if ((numberOfTeams > 2) && (numberOfTeams % 2 == 0)) {
var currentCount = numberOfTeams;
for (var i = 0; i < numberOfMatches; i++) {
var numOne = Math.floor(Math.random() * currentCount);
var numTwo = Math.floor(Math.random() * currentCount);
// Checks if the numbers are the same, or if two spesific teams is against each-other.
while ((numOne == numTwo) || (currentTeams[numOne] == 1 && currentTeams[numTwo] == 3) || (currentTeams[numOne] == 3 && currentTeams[numTwo] == 1)) {
numTwo = Math.floor(Math.random() * currentCount);
}
// Creates a match-array with the two team ID's
matches.push([parseInt(currentTeams[numOne]), parseInt(currentTeams[numTwo])]);
// Simple way to remove them from the start-array.
if (numOne > numTwo) {
currentTeams.splice(numOne, 1);
currentTeams.splice(numTwo, 1);
} else {
currentTeams.splice(numTwo, 1);
currentTeams.splice(numOne, 1);
}
currentCount -= 2;
} // End for-loop
} else {
matches.push([parseInt(currentTeams[0]), parseInt(currentTeams[1])]);
} // End if
currentMatches = matches;
} // End generateTeams
首先,具有不确定的运行时的while循环不是一个好主意。 从统计上讲,这可能需要很长时间才能完成。
此外,还有一个条件使得无法完成比赛:当第1队和第3队呆到最后时,它永远不会终止。 由于您的团队人数可能不多,因此这种情况经常发生。
幸运的是,对于解决给定问题根本不需要使用while循环:更改代码,以便在for循环中,首先选择比赛的第一支球队,将其从currentTeams中删除,然后从中选择第二支球队。剩下的队伍。 这样,不可能两次选择同一支球队。
如果您真的需要两个特别小组的条件,请执行以下操作:首先将它们从currentTeams中删除。 然后为其中一个选择一个对手,这将成为您的第一场比赛。 然后将第二支特别队重新加入名单,并按照前面所述确定其余比赛。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.