我有一个名字数组,选择三个随机名称并将它们放入一个新数组然后打印出来。我怎么能这样做,所以我永远不会使用IF语句获得重复的名称?截至目前,我有时会在生成随机名称时两次使用相同的名称。
<!DOCTYPE html>
<html>
<head>
<title>Students</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showStudents;
}
var text = "";
var randomStudents = []; // Empty array
var students = ["Henning", "Torstein", "Elias", "Ådne", "Dag", "Sander", "Zuz", "Braum", "Sverre", "Kayn", "Katarina", "Vayne"];
function showStudents() {
// Count to three
for (var i = 0; i < 3; i++) {
// Take three random elements from students array and put into empty array
randomStudents += students[Math.floor(Math.random() * students.length)] + "<br/>";
}
// Print out the array with random names
document.getElementById("print").innerHTML = randomStudents;
}
</script>
</head>
<body>
<button id="btn">Show Students</button>
<p id="print"></p>
</body>
</html>
&#13;
答案 0 :(得分:0)
找到学生后,从阵列中删除该学生。这样,下一次就不会出现了。
function showStudents() {
// Copy the array of students
var tmpStudents = students.concat([]);
// Count to three
for (var i = 0; i < 3; i++) {
// Get the random index
var randomIndex = Math.floor(Math.random() * tmpStudents.length);
// Take three random elements from students array and put into empty array
randomStudents += tmpStudents[randomIndex] + "<br/>";
// Remove the student from the array
students.splice(randomIndex, 1);
}
// Print out the array with random names
document.getElementById("print").innerHTML = randomStudents;
}
答案 1 :(得分:0)
我建议使用while循环。当你生成一个不同的名字时,很难猜到。试试这个
for (var i = 0; i < 3; i++) {
// Take random element from students array
studentToAdd = students[Math.floor(Math.random() * students.length)];
// checks if student is already included. Generates another student if true
while (randomStudents.includes(studentToAdd) === true) {
studentToAdd = students[Math.floor(Math.random() * students.length)];
}
// adds generated student
randomStudents += studentToAdd + "<br/>";
}
我还建议在循环之前添加此代码以生成新学生,而不是将其添加到上一组,以防用户多次单击该按钮
randomStudents = [];