![](/img/trans.png)
[英]Splice one item from 2 or more items randomly in Javascript array
[英]Javascript: Trying to randomly move items from one array to another
我一直被困了两个小时,试图从一个数组(玩家)中随机选择一个项目到另一个(team1)中。
我通过对拼接执行其他操作来使其工作,但是不幸的是,拼接本身会使用删除的项目创建一个数组,因此最终获得了一个带有数组的数组。
这是我到目前为止所得到的:
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);
您只需在拼接并推入团队时从数组中选择第一个元素,
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.