我正在编写一个 Discord 机器人。我有一个名为团队的数组,我希望随机分配一个用户一个团队。分配该用户后,我想为下一个用户分配一个团队。
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 - e - 团队 2
一直到第 10 个人,所有英雄都是独一无二的,所有队伍均分,第 1 队 5 个,第 2 队 5 个!
最佳答案
你可以使用 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; }
关于javascript - 从数组中选择在 JavaScript 中没有重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40771592/