2017-08-30 90 views
0

我一直堅持幾個小時,試圖從一個陣列(玩家)隨機選擇一個物品到另一個(隊伍1)。Javascript:試圖隨機地將物品從一個陣列移動到另一個陣列

我已經通過做別的事情與拼接工作,但不幸的是拼接創建一個數組本身與刪除項目,所以我最終得到一個數組與數組。

這是我走到這一步:

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

如果我做的這一切錯了,我很抱歉,還是蠻新的這個網站,幫助表示讚賞。

+0

爲了澄清我想要的東西是隨機從一個數組中移除然後添加到另一個數組 – Buckets

+0

在這裏檢查它是重複https://stackoverflow.com/questions/31829166/move-values-from-one-array-to-another-and-remove-them –

+0

重複的問題 –

回答

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

謝謝你的幫助,爲什麼是這樣的我可以問嗎?我甚至不知道你可以在推送和拼接結束時選擇索引 – Buckets

+0

無論結果如果函數以結構(數組或結構列表)的形式返回數組的結果,我們都可以訪問其中的值索引。 –

+0

對不起還有一個問題,我把它改成了一個while循環,所以我可以把它們分成兩個團隊,它只能工作一部分時間,其他時間將未定義到團隊數組中,你知道爲什麼嗎?這裏是鏈接:https://codepen.io/Buckets/pen/wqQxzP?editors=1111 – Buckets

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); 
相關問題