簡體   English   中英

從數組中選擇JavaScript中沒有重復項

[英]Pick from Array no duplicates in JavaScript

我正在寫一個Discord機器人。 我有一個名為team的數組,我希望隨機為一個團隊分配一個用戶。 分配該用戶后,我想為下一個用戶分配一個團隊。

var teams = ["1","1","1","1","1","2","2","2","2","2"];
var heroes = ["a","b","c","d"...etc];

 for (var i = 0; i < 10; i++) {
        var randomHero = Math.floor(Math.random()*heroes.length)
        var randomTeam = Math.floor(Math.random()*teams.length)
        var hero = heroes[randomHero];
        heroes.splice(randomHero)
        var team = teams[randomTeam];
        message.channel.sendMessage(teams);
        teams.splice(randomTeam)
        message.channel.sendMessage(teams);
        message.channel.sendMessage(users[i] + " - " + hero + ' Team ' + team);
        }
    }

但我不確定如何讓每個人都成為一個團隊,然后刪除該元素。 它不斷提出未定義。

基本上我希望輸出像

人1 - a - 團隊1人2 - b - 團隊2人3 - 電子 - 團隊2

一直到第10人,所有的英雄都是獨一無二的,所有的球隊都是平分的,5隊在第2隊的第5隊!

您可以將Array#splice與第二個參數1一起用作deleteCount ,並將拼接值移動到變量。

 var teams = ["1", "1", "1", "1", "1", "2", "2", "2", "2", "2"], heroes = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"], randomHero, randomTeam, hero, team; for (var i = 0; i < 10; i++) { randomHero = Math.floor(Math.random() * heroes.length) randomTeam = Math.floor(Math.random() * teams.length) hero = heroes.splice(randomHero, 1)[0]; // deleteCount / \\\\\\ take from the array the first element team = teams.splice(randomTeam, 1)[0]; console.log(hero + ' Team ' + team); } console.log(heroes); console.log(teams); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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