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

时间:2015-12-24 09:38:45

标签: javascript html arrays loops random

我需要能够点击一个按钮,然后以随机顺序出现一些不同的名称而不重复任何名称。显示随机名称很简单,但我无法避免重复。这就是我所拥有的,我不明白它为什么不起作用。

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

我知道问题是if语句,但我不知道如何检查名称是否已经显示。如果你知道我检查某些东西的方法有什么不对,或者更好的方法可以避免重复,请告诉我。

4 个答案:

答案 0 :(得分:5)

&#13;
&#13;
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;
}
&#13;
<button onClick="tournament(4)">Tournament Results</button>

<p id="player1"></p>
<p id="player2"></p>
<p id="player3"></p>
<p id="player4"></p>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以克隆原始数组,然后逐个拼接其中的项目。这样你就可以保证每次获得独特的结果。

&#13;
&#13;
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;
    }
}
&#13;
<button onClick="tournament(4)">Tournament Results</button>

<p id="player1"></p>
<p id="player2"></p>
<p id="player3"></p>
<p id="player4"></p>
&#13;
&#13;
&#13;

但请注意,由于它会创建数组的副本,因此对于非常大的玩家阵列,这种方法可能并不理想。

答案 2 :(得分:1)

这是一个通用的函数方法,用随机顺序创建一个包含原始数组值的新数组,不带重复:

&#13;
&#13;
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';
}
&#13;
<pre id="result"></pre>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我将每个选择从数组中分离出来,这样它就无法再次被选中,然后将其写入循环中。

var randomplayer = Math.floor(Math.random()*(players.length));
players = players.slice(randomplayer, 1);
编辑:让我编写整个函数,以防万一有混淆。

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++;
    }
}