我正在写一个Discord机器人。我有一个名为team的数组,我希望随机为一个团队分配一个用户。分配该用户后,我想为下一个用户分配一个团队。
var teams = ["1","1","1","1","1","2","2","2","2","2"];
var heroes = ["a","b","c","d"...etc];
for (var i = 0; i < 10; i++) {
var randomHero = Math.floor(Math.random()*heroes.length)
var randomTeam = Math.floor(Math.random()*teams.length)
var hero = heroes[randomHero];
heroes.splice(randomHero)
var team = teams[randomTeam];
message.channel.sendMessage(teams);
teams.splice(randomTeam)
message.channel.sendMessage(teams);
message.channel.sendMessage(users[i] + " - " + hero + ' Team ' + team);
}
}
但我不确定如何让每个人都成为一个团队,然后删除该元素。它不断提出未定义。
基本上我希望输出像
人1 - a - 第1组 人2 - b - 第2队 人3 - 电子团队2
一直到第10人,所有英雄都是独一无二的,所有队伍都是平分的,5队在第2队的第5队!
答案 0 :(得分:1)
您可以将Array#splice
与第二个参数1一起用作deleteCount
的一个项目,并将拼接值移动到变量。
var teams = ["1", "1", "1", "1", "1", "2", "2", "2", "2", "2"],
heroes = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
randomHero, randomTeam, hero, team;
for (var i = 0; i < 10; i++) {
randomHero = Math.floor(Math.random() * heroes.length)
randomTeam = Math.floor(Math.random() * teams.length)
hero = heroes.splice(randomHero, 1)[0];
// deleteCount / \\\ take from the array the first element
team = teams.splice(randomTeam, 1)[0];
console.log(hero + ' Team ' + team);
}
console.log(heroes);
console.log(teams);
.as-console-wrapper { max-height: 100% !important; top: 0; }