我们假设我有两个包含对象的数组。
var teams = [tobj1, tobj2 ...]
var players = [pobj1, pobj2 ...]
对象有1个属性(名称:teamname / playername)。
var tobj1 = {
name: playername // this comes from an inputfield
}
我要做的是将一支球队随机配对,直到每支球队都有一名球员。团队数量等于玩家数量。
提示:这将是一个足球抽奖应用程序
谢谢您的帮助。
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);
});