Javascript:尝试将项目从一个数组随机移动到另一个数组

时间:2017-08-30 05:28:57

标签: javascript arrays splice

我已经被困了几个小时,现在试图从一个阵列(玩家)中随机选择一个项目(团队1)。

我已经通过使用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);

如果我这样做是对的,我很抱歉,对这个网站来说还是一个新手,感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

你在场景中尝试这样做

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);

答案 1 :(得分:1)

您只需在拼接并推送到团队时选择阵列中的第一个元素,

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);