簡體   English   中英

Javascript:嘗試將項目從一個數組隨機移動到另一個數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM