我需要能够点击一个按钮,然后以随机顺序出现一些不同的名称,而不重复任何名称.显示随机名称很简单,但我无法避免重复.这就是我所拥有的,我不明白为什么它不起作用.
我知道问题是if语句,但我不知道如何检查名称是否已经显示.如果您知道我检查某些东西是否已经被挑选的方法有什么问题或者更好的避免重复的方法,请告诉我.
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;
}