简体   繁体   English

如何使javascript显示随机名称而不重复?

[英]How do I make javascript display random names without repeats?

I need to be able to click on a button, then have a few different names come out in a random order without any name being repeated. 我需要能够点击一个按钮,然后有几个不同的名字以随机顺序出现,没有重复任何名称。 Displaying random names is simple enough, but I cannot avoid repeats. 显示随机名称很简单,但我无法避免重复。 Here's what I have and I don't understand why it doesn't work. 这就是我所拥有的,我不明白为什么它不起作用。

<script>

var players = []
players[0] = "Billy";
players[1] = "Alex";
players[2] = "Kevin";
players[3] = "Fred";

function tournament(amount) {
    var a = 0, i = 0, place = 1;
    randomlyselect:
    while (a<amount) {
        var randomplayer = Math.floor(Math.random()*(players.length));
        if (players[randomplayer] === document.getElementById('player1').innerHTML || document.getElementById('player2').innerHTML || document.getElementById('player3').innerHTML) {
            continue randomlyselect;
            } 
        else {
            document.getElementById('player'+place).innerHTML = players[randomplayer];
            place++;
            a++;
        }
    }

}

</script>

<button onClick="tournament(4)">Tournament Results</button>

<p id="player1"></p>
<p id="player2"></p>
<p id="player3"></p>
<p id="player4"></p>

I know the problem is the if statement, but I don't know how else I would check if a name was already being displayed. 我知道问题是if语句,但我不知道如何检查名称是否已经显示。 If you know what's wrong with my method of checking if something was already picked or a better way of avoiding repeats please let me know. 如果您知道我检查某些东西是否已经被挑选的方法有什么问题或者更好的避免重复的方法,请告诉我。

 var players = [] players[0] = "Billy"; players[1] = "Alex"; players[2] = "Kevin"; players[3] = "Fred"; function tournament(amount) { var randomOrder = shuffle(players) var count = Math.min(amount, randomOrder.length) for (var i = 0; i < count; ++i) { document.getElementById("player" + (i + 1)).textContent = randomOrder[i] } } // http://stackoverflow.com/a/2450976/4339170 function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } 
 <button onClick="tournament(4)">Tournament Results</button> <p id="player1"></p> <p id="player2"></p> <p id="player3"></p> <p id="player4"></p> 

You can clone your original array and then just splice items from it one by one. 您可以克隆原始数组,然后逐个拼接其中的项目。 This way you will guarantied get unique results each time. 这样你就可以保证每次获得独特的结果。

 var players = ["Billy", "Alex", "Kevin", "Fred"]; function tournament(amount) { var clone = players.slice(), i, player; for (var i = 0; i < amount; i++) { player = clone.splice(Math.floor(Math.random() * clone.length), 1); document.getElementById('player' + (i + 1)).innerHTML = player; } } 
 <button onClick="tournament(4)">Tournament Results</button> <p id="player1"></p> <p id="player2"></p> <p id="player3"></p> <p id="player4"></p> 

But be aware that since it creates a copy of the array, this approach might be not ideal in case of really big players arrays. 但请注意,由于它创建了数组的副本,因此对于非常大的播放器阵列,这种方法可能并不理想。

Here's a generic functional method to create a new array with values of the original array in random order without duplicates: 这是一个通用的函数方法,以随机顺序创建一个具有原始数组值的新数组,而不重复:

 function randomizeArrayValues(arr) { return String(Array(arr.length)) .split(',') .map( function () { return this .splice(Math.floor((Math.random()*this.length)), 1) .pop(); }, arr.slice() ); } // example // ------- var players = ["Billy", "Alex", "Kevin", "Fred", "Mary", "Beth"]; var trial = 10; while (trial--) { document.querySelector('#result').textContent += randomizeArrayValues(players).join(', ') + '\\n'; } 
 <pre id="result"></pre> 

I'd slice each selection out of the array so it's not able to be picked again and then write it in the loop. 我将每个选择从数组中分离出来,因此无法再次拾取它然后将其写入循环中。

var randomplayer = Math.floor(Math.random()*(players.length));
players = players.slice(randomplayer, 1);

EDIT: let me write the entire function just in case there's confusion. 编辑:让我写整个函数,以防万一有混乱。

function tournament(){
    var place = 1;
    while(players.length > 0){
        var randomplayer = Math.floor(Math.random()*(players.length));
        document.getElementById('player'+place).innerHTML = players[randomplayer];
        players = players.slice(randomplayer, 1);
        place++;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM