2016-09-24 164 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