2016-09-24 167 views
0

我的Javscript函数不时崩溃浏览器,然后。很少有它崩溃,但你有那些时候,当它的时候。使用萤火虫它看起来就像是一个让所有东西崩溃的while循环。任何人有任何想法?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 
+1

这意味着无论循环内部发生什么,while循环顶部的条件都保持为真。您可以添加一些'console.log()'调用来跟踪涉及的值。 – Pointy

回答

2

是,首先,不是一个好主意,有非确定性的运行时,一个while循环。从统计上来看,它可能需要很长时间才能完成。

此外,还有一个条件,使得它不可能完成:当第1队和第3队留到最后,它永远不会终止。由于您可能没有非常多的团队,这种情况会经常发生。

幸运的是,while循环对于给定问题的救赎并不是必需的:更改代码以便在for循环中,首先选择匹配的第一个组,将其从当前队列中移除,然后选择第二个来自其余的团队。这样,两次选择同一个团队是不可能的。

如果你真的需要这两个特殊团队的条件:先从当前团队中删除它们。然后为他们中的一个选择一个对手,这会让你第一场比赛。然后将第二个特殊团队放回列表中,并按照前面所述确定其余的匹配项。

+0

谢谢,我想首先会尝试为其中一个团队选择一个匹配,然后将其从所有其他团队中移除。 – H0wie12