遍历数组以获取随机字符串,然后删除该字符串,以免再次选择该字符串

时间:2018-12-05 12:23:19

标签: javascript arrays

如上所述!

我正在尝试与一系列团队进行淘汰赛比赛抽签。

我的目标是:

  1. 从一组团队中选择一个随机团队。
  2. 删除该团队,以免再次被选中。
  3. 直到所有团队都被选中为止。

我已经管理了数字1和3,但是努力使2)在我的职责范围内工作。我已经尝试过.push和.splice方法并将其保存到变量中...

这是我到目前为止所拥有的...

 //create an array of teams
 var teams = ['Aston Villa', 'Burnley', 'Arsenal', 'Liverpool', 'Everton',
              'Man Utd', 'Brighton', 'West Ham', 'Spurs', 'Chelsea', 'Man City', 'Fulham']
 var usedTeams = [];
 var pickedTeam;

 //pick a team randomly from the array
 function pickTeam() {
   for (var i = 0; i < teams.length; i++) {
     pickedTeam = teams[Math.floor(Math.random() * teams.length)];
     console.log(pickedTeam);
     usedTeams.push(pickedTeam);


   }
 }

//remove that item from the array

//pick another team

//loop until all teams are picked.

3 个答案:

答案 0 :(得分:2)

Splice除去该值,而不仅仅是获取它。

 pickedTeam = teams.splice(Math.floor(Math.random() * teams.length), 1)[0];

答案 1 :(得分:1)

让函数返回一个名称,然后调用函数team.length次,而不是在函数中循环

const teams = ['Aston Villa', 'Burnley', 'Arsenal', 'Liverpool', 'Everton','Man Utd', 'Brighton', 'West Ham', 'Spurs', 'Chelsea', 'Man City', 'Fulham'];

function pickTeam() {
  const rnd = Math.floor(Math.random() * teams.length);
  return teams.splice(rnd, 1);
}

while (teams.length > 0) {
  console.log(pickTeam(), teams);
}

如果要在console.logs之间暂停,可以使用setTimeout循环。您可以在功能内

const teams = ['Aston Villa', 'Burnley', 'Arsenal', 'Liverpool', 'Everton', 'Man Utd', 'Brighton', 'West Ham', 'Spurs', 'Chelsea', 'Man City', 'Fulham'];

function pickTeam(arr) {
   
   // If there are elements still in the array
   if (arr.length) {

    // Get a random number
    const rnd = Math.floor(Math.random() * arr.length);

    // Grab that random element from the array
    const el = arr.splice(rnd, 1)[0];
    console.log(el, arr);

    // Wait 1 second before calling the function
    // again with the reduced array
    setTimeout(() => pickTeam(arr), 1000);
  }
}

pickTeam(teams);

答案 2 :(得分:0)

 var teams = ['Aston Villa', 'Burnley', 'Arsenal', 'Liverpool', 'Everton', 'Man Utd', 'Brighton', 'West Ham', 'Spurs', 'Chelsea', 'Man City', 'Fulham'];
 var usedTeams = [];
 var teamsQty = teams.length;
 
for(let i=0; i<teamsQty; i++){
  let pickedTeam;
  pickedTeam = teams[Math.floor(Math.random()*teams.length)];
  usedTeams.push(pickedTeam);
  teams.splice(teams.indexOf(pickedTeam),1);
};

console.log(usedTeams);