首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >While-loop崩溃浏览器

While-loop崩溃浏览器
EN

Stack Overflow用户
提问于 2016-09-25 01:04:36
回答 1查看 332关注 0票数 0

我的Javscript函数时不时地使浏览器崩溃。它崩溃的次数很少,但当它崩溃的时候,你会遇到这样的情况。使用firebug,看起来是while循环导致了所有东西的崩溃。有谁知道吗?

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-25 02:41:11

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

此外,还有一个条件使其无法完成:当团队1和3一直留到最后,它永远不会结束。由于你的团队数量可能不是很多,所以这种情况会经常发生。

幸运的是,为了解决给定的问题,while循环根本不是必需的:更改代码,以便在for循环中,首先选择比赛的第一支球队,将其从currentTeams中删除,然后从其余球队中选择第二支球队。在这种情况下,不可能两次选择同一个团队。

如果您确实需要两个特殊团队的条件:首先从currentTeams中删除它们。然后为他们中的一个选择一个对手,这将是你的第一场比赛。然后将第二支特殊球队放回列表中,并按照前面的描述确定剩下的比赛。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39678865

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档