Javascript: 尝试将项目从一个数组随机移动到另一个数组
Javascript: Trying to randomly move items from one array to another
我已经被困了几个小时,现在试图随机 select 从一个数组(玩家)到另一个数组(team1)的一个项目。
我通过使用 splice 做其他事情来让它工作,但不幸的是 splice 使用删除的项目创建了一个数组,所以我最终得到了一个带有数组的数组。
这是我目前得到的:
var players = ["P1", "P2", "P3", "P4"];
var team1 = [];
var team2 = [];
var select = Math.floor(Math.random() * players.length);
var tmp;
if (team1.length < 2) {
tmp.push(players.splice(select, 1));
team1.push(tmp.pop);
}
console.log(team1);
console.log(tmp);
console.log(players);
如果我做错了,对不起,这个网站还很新,感谢帮助。
你在你的场景中这样尝试
var players = ["P1", "P2", "P3", "P4"];
var team1 = [];
var team2 = [];
var temp = players.slice();
for(i=0; i<temp.length; i++){
var select = Math.floor(Math.random() * temp.length);
console.log(select);
if (team1.length <= temp.length/2) {
team1.push(temp[select]);
}
temp.splice(select, 1);
}
team2 = temp.slice();
console.log('team 1 ---',team1);
console.log('team 2 ---',team2);
console.log('players ---', players);
你只需要 select 数组中的第一个元素,同时拼接和推送到组,
var players = ["P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8"];
var team1 = [];
var team2 = [];
var tmp = [];
while (team1.length < 4) {
tmp.push(players.splice(Math.floor(Math.random() * players.length - 1), 1)[0]);
team1.push(tmp.pop());
}
while (team2.length < 4) {
tmp.push(players.splice(Math.floor(Math.random() * players.length - 1), 1)[0]);
team2.push(tmp.pop());
}
console.log(team1);
console.log(team2);
console.log(tmp);
console.log(players);
我已经被困了几个小时,现在试图随机 select 从一个数组(玩家)到另一个数组(team1)的一个项目。
我通过使用 splice 做其他事情来让它工作,但不幸的是 splice 使用删除的项目创建了一个数组,所以我最终得到了一个带有数组的数组。
这是我目前得到的:
var players = ["P1", "P2", "P3", "P4"];
var team1 = [];
var team2 = [];
var select = Math.floor(Math.random() * players.length);
var tmp;
if (team1.length < 2) {
tmp.push(players.splice(select, 1));
team1.push(tmp.pop);
}
console.log(team1);
console.log(tmp);
console.log(players);
如果我做错了,对不起,这个网站还很新,感谢帮助。
你在你的场景中这样尝试
var players = ["P1", "P2", "P3", "P4"];
var team1 = [];
var team2 = [];
var temp = players.slice();
for(i=0; i<temp.length; i++){
var select = Math.floor(Math.random() * temp.length);
console.log(select);
if (team1.length <= temp.length/2) {
team1.push(temp[select]);
}
temp.splice(select, 1);
}
team2 = temp.slice();
console.log('team 1 ---',team1);
console.log('team 2 ---',team2);
console.log('players ---', players);
你只需要 select 数组中的第一个元素,同时拼接和推送到组,
var players = ["P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8"];
var team1 = [];
var team2 = [];
var tmp = [];
while (team1.length < 4) {
tmp.push(players.splice(Math.floor(Math.random() * players.length - 1), 1)[0]);
team1.push(tmp.pop());
}
while (team2.length < 4) {
tmp.push(players.splice(Math.floor(Math.random() * players.length - 1), 1)[0]);
team2.push(tmp.pop());
}
console.log(team1);
console.log(team2);
console.log(tmp);
console.log(players);