我们假设我有两个包含对象的数组。
void addPlayer(Player &newPlayer)
{...}
void addPlayer(string in_first_name, string in_last_name)
{
Player newP(in_first_name, in_last_name);
addPlayer(newP);
}
对象有1个属性(名称:teamname / playername)。
var teams = [tobj1, tobj2 ...]
var players = [pobj1, pobj2 ...]
我要做的是将一支球队随机配对,直到每支球队都有一名球员。团队数量等于玩家数量。
提示:这将是一个足球抽奖应用
感谢您的帮助。
答案 0 :(得分:0)
let players = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
const teams = [ { name: '1' }, { name: '2' }, { name: '3' } ];
const appairedTeams = teams.map( team => {
let index = Math.floor(Math.random() * players.length);
team.player = players[index];
players.splice(index, 1);
return team;
});
或者,如果您不想创建新对象:
let players = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
let teams = [ { name: '1' }, { name: '2' }, { name: '3' } ];
teams.forEach( team => {
let index = Math.floor(Math.random() * players.length);
team.player = players[index];
players.splice(index, 1);
});
或者如果您只想要播放器的名称:
let players = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
let teams = [ { name: '1' }, { name: '2' }, { name: '3' } ];
teams.forEach( team => {
let index = Math.floor(Math.random() * players.length);
team.playerName = players[index].name;
players.splice(index, 1);
});